Created
February 20, 2020 15:14
-
-
Save iampeterbanjo/383cafdbe4f269dfb6f66f6b2ed30e95 to your computer and use it in GitHub Desktop.
Custom error in Typescript that has stack information
This file contains 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
// 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