Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Promise be rejected with Error or string? [duplicate]

I am writing a code that heavily uses ECMAScript 6-like promises in Javascript.

I cannot decide, if it's more "correct" to reject promise with a string or with an error, since I have seen both of these patterns being used.

That is, if it's better to call

return new Promise(response, reject) {
    reject("Sky is falling.");
}

or

return new Promise(response, reject) {
    reject(new Error("Sky is falling."));
}
like image 947
Karel Bílek Avatar asked Mar 29 '15 22:03

Karel Bílek


1 Answers

A look at Mozilla's documentation is helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject

Promise.reject("Testing static reject").then(function(reason) {   // not called }, function(reason) {   console.log(reason); // "Testing static reject" });  Promise.reject(new Error("fail")).then(function(error) {   // not called }, function(error) {   console.log(error); // Stacktrace }); 

It shows both strings and errors as valid "reasons" for a rejection. The main thing (I think) is that the "reason" should be meaningful.

If a stack trace is helpful then it may be better to provide an error. If a simple string is all that's needed, then it will suffice.

like image 104
bvaughn Avatar answered Sep 20 '22 18:09

bvaughn