抓住所有未处理的javascript承诺拒绝 [英] Catch all unhandled javascript promise rejections
问题描述
我想抓住在javascript Promise中发生的所有未处理的异常/拒绝。是否有一个很好的方法来捕获它们而不在Promise链的每一端添加 .catch(..)
? (如果忘记添加此内容,错误会默默消失)。
I would like to catch all unhandled exceptions/rejections that take place within a javascript Promise. Is there a good method for catching them without adding a .catch(..)
on each end of the Promise chain? (in case of forgetting to add this, the error silently disappears).
Google Chrome中的开发者控制台可以记录它们,我也想在生产中记录它们环境。
The developer console in Google Chrome can log them, I like to log them as well in a production environment.
对于普通的javascript异常,我使用 window.onerror
函数,但是Promise的错误调用了这个函数。
For normal javascript exceptions I use the window.onerror
function, but the errors from a Promise call this function.
示例:
window.onerror = function (e) {
alert("unhandled error: " + e);
};
var p = new Promise(function (resolve, reject) {
var nullObject = null;
// Raise a TypeError: Cannot read property 'forceNullError' of null
var x = nullObject.forceNullError();
resolve();
});
p.then(function () { alert('success'); });
JSFiddle: https: //jsfiddle.net/f7zwej6L/
JSFiddle: https://jsfiddle.net/f7zwej6L/
*)我注意到WinJS有 .done(..)
我想要的方法,但Native Promises没有。
*) I noticed that WinJS has a .done(..)
method for what I want, but Native Promises don't.
推荐答案
全世界都在等待 unhandledrejection
和 rejectionhandled
事件。截至2016年3月,Chrome现在是第一个支持它。
The whole world is waiting for the unhandledrejection
and rejectionhandled
events. As of March 2016, Chrome is now the first to support it.
示例:
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled rejection (promise: ', event.promise, ', reason: ', event.reason, ').');
});
Mozilla开发人员:
onrejectionhandled , onunhandledrejection
Mozilla Developer: onrejectionhandled, onunhandledrejection
Chromium Issues: 495801, 393913
这篇关于抓住所有未处理的javascript承诺拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!