I\'d like to create my own error class in TypeScript, extending core Error to provide better error handling and customized reporting. For example, I want to cre
For Typescript 3.7.5 this code provided a custom error class that also captured the correct stack information. Note instanceof does not work so I use name instead
// based on https://gunargessner.com/subclassing-exception
// example usage
try {
throw new DataError('Boom')
} catch(error) {
console.log(error.name === 'DataError') // true
console.log(error instanceof DataError) // false
console.log(error instanceof Error) // 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;
}
}
There are some other alternatives and a discussion of the reasons.