Why does onerror not intercept exceptions from promises and async functions

纵饮孤独 提交于 2019-12-06 14:14:49

You can add a window handler for onunhandledrejection, since unhandled Promise rejections aren't exactly the same things as errors. Check the results of the below snippet in your browser console (not the snippet console, it'll have problems trying to display the big object):

window.onerror = function(message, source, lineno, colno, error) {
  console.log('onerror handler logging error', message);
  return true;
}
window.onunhandledrejection = function(message, source, lineno, colno, error) {
  console.log('onunhandledrejection handler logging error', message);
  return true;
}


function rejectPromise() {
  return Promise.reject(new Error('rejected promise'));
}

async function throwAsync() {
  throw new Error('async exception');
}

function fail() {
  throw new Error('exception');
}

rejectPromise().then(() => console.log('success'));
throwAsync();
fail();

You can add addEventListener to fix that as throw new Exception() will be raising an error event. So fail() will raise an error event

window.addEventListener("error", function (e) {
   alert("Error occurred: " + e.error.message);
   return false;
})

window.addEventListener('unhandledrejection', function (e) {
  alert("Error occurred: " + e.reason.message);
})

Hope this helps !!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!