为什么onerror不会拦截来自promise和async函数的异常 [英] Why does onerror not intercept exceptions from promises and async functions

查看:177
本文介绍了为什么onerror不会拦截来自promise和async函数的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用onerror拦截和记录在我的JavaScript应用程序中发生的所有错误.除了使用promises或async函数时,这可以按预期工作.

I want to use onerror to intercept and log all errors that occur in my JavaScript application. This works as expected except when using promises or async functions.

在下面的片段中,按预期截取了由fail引发的异常,但是rejectPromisethrowAsync而不是调用onerror处理程序总是在控制台中显示Uncaught (in promise) Error?

In the following snipped the exception thrown by fail is intercepted as expected but rejectPromise and throwAsync instead of invoking the onerror handler always show an Uncaught (in promise) Error in the console?

我如何始终在使用promise和异步功能的代码库中拦截所有错误?

How can I always intercept all errors in a code base that uses promises and async functions?

window.onerror = function(message, source, lineno, colno, error) {
  console.log('onerror 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();

推荐答案

您可以为onunhandledrejection添加窗口处理程序,因为未处理的Promise拒绝与错误并不完全相同.在您的浏览器控制台中检查以下代码片段的结果(不是代码片段控制台,它在显示大对象时会出现问题):

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();

这篇关于为什么onerror不会拦截来自promise和async函数的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆