简体   繁体   English

Promise.reject消息应该包含在Error中吗?

[英]Should a Promise.reject message be wrapped in Error?

Using the native (ES6) Promise . 使用原生(ES6) 承诺 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. 没有错误 - 没有堆栈跟踪。

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. 就像使用try / catch一样,如果你将.catch添加到抛出拒绝中,你希望能够记录堆栈跟踪,为你抛出字符串废墟。

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. 在大型(10K + LoC)应用程序中,拒绝堆栈中的痕迹确实使得轻松的远程错误捕获与办公室中漫长的夜晚之间存在差异。

I'm recommending to use Error object only (not a string) for sending the reasons. 我建议仅使用Error对象 (不是字符串)来发送原因。

Justification 理由

Other parts of code are generating the Errors inside the Promise rejection reason... 代码的其他部分在Promise拒绝原因中生成Errors ...

If some code fails the exception returns the Error object. 如果某些代码失败,则异常将返回Error对象。 Also if you will call any external library, which does not support the Promise, it will throw the Error object when something fails. 此外,如果您将调用任何不支持Promise的外部库,它将在出现Error时抛出Error对象。 If one of errors mentioned above occurs inside the Promise, it will be transformed into catch with Error object. 如果上面提到的错误之一发生在Promise中,它将被转换为带有Error对象的catch

Therefore if you will use the string as promise rejection reason, you have to expect that the catch can occurs with your string (part of your code) or Error (when some general error occurs). 因此,如果您将string用作承诺拒绝原因,则必须预期捕获可能发生在您的string (代码的一部分)或Error (发生某些一般错误时)。 So you will have to use ugly code (err.message || err) everywhere, when you have to handle the error. 所以当你必须处理错误时,你将不得不在任何地方使用丑陋的代码(err.message || err)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM