es6 promises swallow type errors

穿精又带淫゛_ 提交于 2019-12-07 03:11:11

问题


I want the browser to show an error message when a type error occurs.
errors like can not read property something of undefined or undefined reference.

new Promise(function(resolve,reject){
    // do stuff ...
    reject('something logical is wrong');
}).catch(e => console.error(e));

new Promise(function(resolve,reject){
    // do stuff, and a syntax error :/
    var a = { };
    a.something.otherthing = 1; /* we have an error here */
    // ... 
}).catch(e => console.error(e));

In the first example the error is a logical one, and its fine to catch it in the catch(..) block.
But in the second example it is a clear development error, which happens all the time while developing new stuff. I don't want to catch it, i want the browser to show me the error like other errors in the console. I want to be able to turn on chrome pause on exceptions and see the state of other variables. I want to see the stack trace in console.
I want it to act like a normal error.

Any idea?


回答1:


Unlike exceptions in synchronous code, which become uncaught as soon as code returns to idle, a browser generally doesn't know the logical end of a promise-chain, which is where an asynchronous error could be considered uncaught. Chains are dynamically assembled after all, and therefore better be terminated with a final .catch at the logical end of the chain i.e. the asynchronous equivalent of idle.

Having a final .catch(e => console.error(e)) seems very reasonable to me, but you're right that browsers tend to display these errors differently from uncaught exceptions. If you want them to appear the same, you can use this trick:

.catch(e => setTimeout(() => { throw e; }))

This will throw e, containing the original stack trace and line number, on the very next cycle, and outside of the promise chain, where nothing will catch it and it will be reported as uncaught. We use setTimeout to overcome the default behavior of .catch which is to capture any exceptions in-chain in case you intend to keep on chaining.

With this, I hope you see that any differentiation between "logical" and other errors is irrelevant. Any error that makes it to the tail of the chain was fatal to the chain i.e. uncaught (though of course you can triage "logical" from other errors in the final catch and display them differently if you choose.)




回答2:


chrome has an option Pause on Caught Exceptions in Sources tab, i enabled that option and Pause on Exceptions feature is working fine now.



来源:https://stackoverflow.com/questions/33376308/es6-promises-swallow-type-errors

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