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?