Skip to content

Instantly share code, notes, and snippets.

@iampeterbanjo
Created February 20, 2020 15:14
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 iampeterbanjo/383cafdbe4f269dfb6f66f6b2ed30e95 to your computer and use it in GitHub Desktop.
Save iampeterbanjo/383cafdbe4f269dfb6f66f6b2ed30e95 to your computer and use it in GitHub Desktop.
Custom error in Typescript that has stack information
// based on https://gunargessner.com/subclassing-exception
// example usage
try {
throw new DataError('Boom')
} catch(error) {
error.name === 'DataError' // true
}
class DataError {
constructor(message: string) {
const error = Error(message);
// set immutable object properties
Object.defineProperty(error, 'message', {
get() {
return message;
}
});
Object.defineProperty(error, 'name', {
get() {
return 'DataError';
}
});
// capture where error occured
Error.captureStackTrace(error, DataError);
return error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment