简体   繁体   中英

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.

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.

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.

I'm recommending to use Error object only (not a string) for sending the reasons.

Justification

Other parts of code are generating the Errors inside the Promise rejection reason...

If some code fails the exception returns the Error object. Also if you will call any external library, which does not support the Promise, it will throw the Error object when something fails. If one of errors mentioned above occurs inside the Promise, it will be transformed into catch with Error object.

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). So you will have to use ugly code (err.message || err) everywhere, when you have to handle the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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