Categories
Intermediate

Angular Typescript (async) Catch-Finally Decorator

Hey Guys! Today I want to talk about error handling for async and non-async Typescript methods. Let’s take a look at some error-prone typescript method:

someRegularMethod(){

// code
someDangerousMethod();
//more code
}

So what if some Dangerous Method threw an exception? Solution try-catch!

someRegularMethod(){
// code
try{
someDangerousMethod();

}catch(err)[

]
//more code

}

But this bloats the code a bit, right?

So what’s the alternative?  Catch Decorator. Click on the image below to access the code:

Using the catch decorator your code will look like this:

@Catch(Error, (err: Error, ctx) => ctx.handleError(err), (ctx) => ctx.finalizeRequest())
someRegularMethod(){

// code
someDangerousMethod();
//more code
}

This mimics the try-catch-finally block. The first parameter is the Error type, the second is the error handler, and the third is the finally block. This saves us the trouble to write it in the method itself.

You can even use it with async methods: 

@Catch(Error, (err: Error, ctx) =>  ctx.handleError(err), (ctx) => ctx.finalizeRequest())
async someRegularMethod(){
 
 // code
 await someDangerousMethod();
 //more code
}

So what do you think? Will you stop using regular try-catch blocks?

Leave a Reply

Your email address will not be published. Required fields are marked *