Promise.reject 消息是否应该包含在 Error 中? [英] Should a Promise.reject message be wrapped in Error?

查看:68
本文介绍了Promise.reject 消息是否应该包含在 Error 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用原生 (ES6) Promise.我是否应该拒绝 错误:

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

浏览器行为有何不同?

推荐答案

是的,绝对应该.字符串不是错误,当您遇到错误时,通常意味着出现问题,这意味着您真的会享受良好的堆栈跟踪.没有错误 - 没有堆栈跟踪.

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 一样,如果您将 .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 消息是否应该包含在 Error 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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