@Catch - error handling
Easy way to handle errors thrown from a metho

Overview

The @Catch() decorator provides an easy way to handle errors thrown from any method. Also, it's provide a way to handle errors based on type
The @Catch decorator can be applied on class level or method level

Usage

The Catch decorator can be use with error types or without declaring on error types
Catch(handler: (err: Error | SugoiError) => any)
Catch(handler: (err: Error | SugoiError) => any, ...errors: Array<string |Error | SugoiError>)

Catch all errors

1
@Catch(() => null)// will handle all the Errors and return null in case of an error
2
export class DecoratorCatch{
3
private static number: number = 1;
4
private instanceNumber: number = 0;
5
6
catchCheck(numberToCheck: number){
7
if(numberToCheck === 0){
8
throw new MyError('testing1',321);
9
}
10
else if(numberToCheck === 1){
11
throw new MyError2('testing2',321);
12
}
13
else if(numberToCheck === 2){
14
throw new Error('test generic error');
15
}
16
return this.instanceNumber;
17
}
18
}
Copied!

Declaring error type

While declaring an error type only error types of those type will be handled by the handler method

Example

1
@Catch(() => null,
2
'MyError', MyError2)// will handle Errors of class 'MyError' only
3
// or instance of MyError2
4
// Returns null in case of an error
5
export class DecoratorCatch{
6
private static number: number = 1;
7
private instanceNumber: number = 0;
8
9
@Catch(function(err){
10
console.log('catcher got an error', err);
11
return this.instanceNumber - 1
12
}, 'Error') // will handle Errors of class 'Error' only
13
catchCheck(numberToCheck: number){
14
if(numberToCheck === 0){
15
throw new MyError('testing1',321);
16
}
17
else if(numberToCheck === 1){
18
throw new MyError2('testing2',321);
19
}
20
else if(numberToCheck === 2){
21
throw new Error('test generic error');
22
}
23
return this.instanceNumber;
24
}
25
}
Copied!
Last modified 2yr ago