应该将Promise.reject消息包装在错误中? [英] Should a Promise.reject message be wrapped in Error?
问题描述
Using the native (ES6) Promise. Should I reject with an Error:
Promise.reject(new Error('Something went wrong'));
或者我应该拒绝一个字符串:
Or should I just reject with a string:
Promise.reject('Something went wrong');
浏览器行为有什么区别?
And what is the difference in browser behaviour?
推荐答案
是的,这绝对应该是。 字符串不是错误当你有错误时,通常意味着出现问题,这意味着你真的会喜欢一个很好的堆栈跟踪。没有错误 - 没有堆栈跟踪。
Yes, it most definitely should. A string is not an error, when you have errors usually it means something went wrong which means you'd really enjoy a good stack trace. No error - no stack trace.
就像try / catch一样,如果将$ code> .catch 添加到抛出的拒绝,你想要能够记录堆栈跟踪,为您丢弃字符串废墟。
Just like with try/catch, if you add .catch
to a thrown rejection, you want to be able to log the stack trace, throwing strings ruins that for you.
我在手机上,所以这个答案相当短,但我真的不能强调这是多么重要。在大型(10K + LoC)应用程序中,垃圾邮件中的痕迹真的在办公室中轻松的远程错误狩猎和漫长的夜晚之间有所区别。
I'm on mobile so this answer is rather short but I really can't emphasize enough how important this is. In large (10K+ LoC) apps stack traces in rejections really made the difference between easy remote bug hunting and a long night in the office.
这篇关于应该将Promise.reject消息包装在错误中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!