在 javascript 中,您可以覆盖全局 onerror,捕获大部分错误:
window.onerror = function(message, source, lineno, colno, error) { ... };
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
在你的情况下:
window.onerror = function(message, source, lineno, colno, error) {
console.error(message);
alert(message);
return false
};
function main() {
// This works
throw new Error('Error from main()');
document.querySelector('button').addEventListener('click', function() {
// This doesn throw
throw new Error ('Error from click callback');
})
}
main();
一些额外的信息:
https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror
如果 Promise 会引发错误,则添加在问题之后,让我们测试一下:
window.onerror = (message, source, lineno,colno,error)=>{
console.error(`It does!, ${message}`);
};
const aFn = ()=>{
return new Promise((resolve)=>{
setTimeout(()=>{
throw new Error("whoops")
}, 3000);
});
}
aFn();
结果:
VM1163:2 It does!, Script error.
window.onerror @ VM1163:2
error (asynchroon)
(anoniem) @ VM1163:1
VM1163:7 Uncaught Error: whoops
at <anonymous>:7:19