Last active
January 21, 2020 07:44
-
-
Save arifmahmudrana/9bac68cc0f761b10872be0e7944e8bd6 to your computer and use it in GitHub Desktop.
Typescript error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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