0

Suppose I have a long-running async process called calculateFrobnitz, which is intended to return a promise. Suppose it must take an integer, because a frobnitz is really just a ratio.

My question is this - when dealing with functions that return promises, is best practice to use Errors to signal error states, or just rejected promises?

Option 1:

var frobnitz = 22; 

var calculateFrobnitz = (input) => {
   if(typeof input === 'string') {
     throw new Error('Need an integer');
   }

   return Promise.resolve(input/frobnitz);
};

The advantage I see here is that you can distinguish between the case when there was an error using the API (passed a string) from the case where the actual calculation failed (promise rejected). The disadvantage is that you might saddle all callers with crappy try/catch blocks.

Option 2:

var frobnitz = 22; 

var calculateFrobnitz = (input) => {
   if(typeof input === 'string') {
     return Promise.reject('Need an integer');
   }

   return Promise.resolve(input/frobnitz);
};

The advantage here is that the answer is always a promise, nicely chain able, and of course you can use catch(). The disadvantage is that without parsing the error that comes back, you can't tell the difference between "caller didn't use the API right" and "error doing the frobnitz calculation".

Are there best practices for error handling with promises?

FrobberOfBits
  • 17,634
  • 4
  • 52
  • 86
  • Not an expert on the matter, but what I find most convenient is to extend the Error object and create custom errors and catch them using .catch(). That way I can chain .catch() for the errors that I want to handle and let all other errors pass down to a generic .catch() handler that handles all unhandled errors. For example you could have a ValidationError type that you catch for when validation fails. But the discussion then becomes whether the Error object should be extended at all and how to do it correctly. Seems to be a lot of opinions around that. – grimurd May 25 '16 at 21:07
  • Also have a look at [Should a Promise.reject message be wrapped in Error?](http://stackoverflow.com/q/26020578/1048572). To tell the difference between the exceptions, you should reject with different errors (or different messages at least). – Bergi May 26 '16 at 01:49

0 Answers0