Error handling with async await

I’m playing around with async await lately to refactor our frontend data fetching layer. Naturally I wondered how I’m supposed to catch errors with async await.

It’s surprisingly straight fowrward: Just use a try catch block.

Say I have a function that returns a promise which errors (Like a failed http request for example).

var asyncError = function(){
  return new Promise(function(resolve, reject){
    reject('boom');
  });
}

All I need to do is wrap the await statement in a try catch block:

(async function(){
  try{
    return await asyncError();  
  }catch(err){
    console.log('Oh my god there\'s an error', err);
  }
}());

It works just like you’d expect.

I love the async await spec, it’s so powerful yet it’s such a minimal addition to the JavaScript syntax. You might or might not be aware that async await spec comes from c#, in fact it’s almost identical. Nod of respect to Microsoft!