Skip to content

Instantly share code, notes, and snippets.

@arifmahmudrana
Last active January 21, 2020 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arifmahmudrana/9bac68cc0f761b10872be0e7944e8bd6 to your computer and use it in GitHub Desktop.
Save arifmahmudrana/9bac68cc0f761b10872be0e7944e8bd6 to your computer and use it in GitHub Desktop.
Typescript error handling
abstract class BaseError extends Error {
abstract status: number;
}
class ValidationError extends BaseError {
status: number = 422;
constructor(message?: string) {
super(message);
this.name = this.constructor.name;
}
}
/* class InternalServerError extends BaseError {
status: number = 500;
constructor(message?: string) {
super(message);
this.name = this.constructor.name;
}
} */
class InternalServerError extends BaseError {
status: number = 500;
constructor(message?: string, status?: number) {
super(message);
this.name = this.constructor.name;
if (status) {
this.status = status;
}
}
}
class MyError {
name: string;
constructor(public message?: string) {
this.name = this.constructor.name;
Error.captureStackTrace(this, MyError);
}
}
const error_handler = (err: Error) => {
if (err instanceof BaseError) {
console.log('====================================');
console.log((err as BaseError).status, err.message);
console.log('====================================');
}
console.log('==================error_handler==================');
console.log(err.stack);
console.log('==================error_handler==================');
};
const error_factory = (type: string, ...rest: any) => {
switch (type) {
case 'InternalServerError':
return new InternalServerError(...rest);
case 'ValidationError':
return new ValidationError(...rest);
case 'MyError':
return new MyError(...rest);
default:
return new Error(...rest);
}
};
try {
// throw new InternalServerError('Something went wrong');
// throw new ValidationError('Validation error');
// throw new MyError('Some error');
throw error_factory('InternalServerError', 'Something went wrong', 504);
throw error_factory('ValidationError', 'Validation error');
throw error_factory('MyError', 'Some error');
throw error_factory('Not found', 'Not Found');
} catch (error) {
console.log('=========================================');
console.log(error.stack);
console.log('=========================================');
error_handler(error);
}
// error_handler(new ValidationError('Validation error'));
// error_handler(new InternalServerError('Something went wrong'));
// error_handler(new CustomError(new Error('something went wrong'))); // doesn't work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment