What are the built-in JavaScript error types, and how do you tell them apart?
An error object carries more than a message. The useful properties are the name, the message, the stack, and the cause, which links the error to whatever failed underneath it.
class AppError extends Error {
constructor(message, cause) {
super(message);
this.name = 'AppError';
this.cause = cause;
}
}
// Inspect an error properly.
function describe(err) {
return {
name: err.name,
message: err.message,
isError: err instanceof Error,
cause: err.cause ? err.cause.message : null
};
}
const low = new Error('disk full');
const high = new AppError('could not save profile', low);
console.log(describe(high));
// { name: 'AppError', message: 'could not save profile', isError: true, cause: 'disk full' }
console.log(describe(low).cause); // null
// Errors can also be gathered together.
const aggregate = new AggregateError([low, new Error('timeout')], 'several failures');
console.log(aggregate.errors.length); // 2
console.log(aggregate.message); // 'several failures'The stack property is the one that earns its keep in real work. It records the call stack at the point where the error was created, and that is what you look at when you are trying to work out where something went wrong. It is worth knowing that the stack is captured when the error is constructed, so if you create an error and throw it later the stack points at the place where it was created rather than the place where it was thrown.
The cause property is newer, and it is worth adopting. It lets you wrap a low level failure inside a higher level one without losing the original, so the log shows both the message that your user cares about and the underlying reason. You set it by passing an options object as the second argument to the Error constructor.
There is one caution to keep in mind. Because any value at all can be thrown, you should never assume that the caught value is an Error object. Code that reads err.message without checking first will fail in a confusing way when somebody throws a string, and that happens often enough in older code that a careful check is worth writing.