In this post I will show how to add error handling when using async/await in TypeScript.

In my previous post I showed how to use async/await with promises.

In this post I will expand on this by adding error handling.

Error handling with promises

Error handling in promises is done using a catch, or a then with an error handler callback. Both are valid, but there is a subtle difference between using a “catch” vs. the error callback in a “then”.

The difference is that the error callback of “then” won't trigger if there is an error when executing the success callback of the same then. Catches are chained with a previous then, so you don't have this problem. Any error in a prior then will be caught by the catch.

Async/Await

One of the goals of async/await is to make asynchronous code appear more syntactically similar to synchronous code. This is also true for error handling.

When trapping errors in async await calls we use regular try catch clauses.

I have expanded the example from my previous post to contain some basic error handling.

async getPersonFullNameWithTryCatch() { try { let response = await fetch('./data/person2.json'); ….. } catch(e) { console.log('there was an error'); console.log(e); } }

All I have done is wrap the original code in a try catch.