Posted over 4 years ago. Visible to the public. Repeats.

JavaScript: Don't throw exceptions from async functions

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise.

The full story

When your function returns a promise ("async function"), try not throw synchronous exceptions when encountering fatal errors.

So avoid this:

Copy
function foo(x) { if (!x) { throw "No x given" } else return new Promise(function(resolve, reject) { ... }); } }

It's hard to handle errors when calling foo, since we need to handle both a synchronous throw and an asynchronous rejection. Look how much code we need to handle failures of the foo() above:

Copy
try { function onFulfilled() { ... } function onRejected() { // handle async failure } foo(x).then(onFulfilled, onRejected); } catch (e) { // handle synchronous failure }

Instead you should signal an error by returning a rejected promise:

Copy
function foo(x) { if (!x) { return Promise.reject("No x given") } else return new Promise(function(resolve, reject) { ... }); } }

Now your caller only needs to handle async failure:

Copy
function onFulfilled() { ... } function onRejected() { // handle async failure } foo(x).then(onFulfilled, onRejected);

Converting exceptions to rejected promises

If you have an existing function that throws synchronous errors, and you want to convert all these throws to rejected promises, you can make the function async:

Copy
async function foo() { throw "error" } foo() // returns Promise.reject("error") await foo() // throws "error"

As an alternative you can use the behavior that exceptions thrown in promise callbacks will automatically be caught and converted to a rejected promise instead. That means if you really want to throw from foo() (or if you're calling another function that throws) you can wrap your code into the callback of a resolved promise:

Copy
function foo(x) { var promise = Promise.resolve(); return promise.then(function() { if (!x) { throw "No x given" } else return new Promise(function(resolve, reject) { ... }); } }); }

This behavior is in all Promises/A+ compatible implementations like native promises, jQuery 3+ deferreds or Bluebird. Deferreds in jQuery 1 and 2 do not have this behavior.

Read more

Promise-based functions should not throw exceptions

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more