https://medium.com/geekculture/how-to-strongly-type-try-catch-blocks-in-typescript-4681aff406b9

1*8xZkF6mq2knNGxbaAHt2sw.jpeg

Oops

Unfortunately Javascript does not support multiple catch(error) to allow you to run a different code based on the error type. But, there are ways we can improve error handling in our single catch statement to leverage the power of classes and the instanceof operator. Lets see an example of catching different exceptions in a language such as C#.

Good ol’ classic C# try/catch

The above example is awesome! We don’t have to do any manual type checking on the exception, we don’t have any if statements to make our code less readable and it also gives us the ability to extract the different bits of code in each catch statement in its own function and reuse it in other try/catch blocks. Perfect!

Now lets see a typical try/catch block in TypeScript.

Now this kinda sucks. You have no indication of what the cause of the exception might be, you have no idea what the structure of error parameter might be and you are left debugging and doing something like console.log(error.message) and hoping that there is a property there called message that holds some relevant information.

We might assume, considering that we are catching an error that may result in a http call that we have the status code in error.status or error.statusCode, but again, we are assuming and until we debug/test we don’t know. Also, there might be some other error that resulted along the way which has gives a completely different structure of the error in our catch.

One reason handling errors from HTTP requests is so annoying is that you cannot set a type for the error object and you must rely on convention with the backend folks on how the error object should look. And, of course, this changes from project to project since everyone has a different structure for the error object.

Note: you should have a convention with the API regarding the DTO in case of an error.

Cleaning up the mess

Next up, lets define some classes as our error response DTOs.

Continuing the example, I am going to use Axios and its interceptors mechanism. If you are not familiar (or if you are curious, a deep dive in Axios is not required for what we are doing here) you can checkout the docs here.

So, lets do a bit of setup with Axios. What I am doing, and what I usually do when working with Axios, is to use an interceptor to run a bit of code when a request completes and if I get an error status code I map the default DTO to a known type which I declare and have control over.

Of course, if you use a framework or library you may have different configuration for intercepting these errors. Like HTTP Interceptors for Angular.

A bit of explanation — Axios.interceptors.response.use has 2 parameters: