Sub topic 8
Attaching the Original Error with cause
This chapter assumes you can write a custom error class that extends Error and passes arguments to super, as covered earlier. You should also be comfortable with try/catch.
The problem cause solves
Code often catches a low-level error and throws a clearer one. Before ES2022, the usual way to do that lost information:
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Settings file is not valid JSON');
}
}The new error tells the caller what went wrong in terms they understand. The original SyntaxError is gone, though, along with its message and stack trace pointing to the bad character. Some developers put the original message into the new one, and others added an ad hoc originalError property. Neither approach was standard, so tools could not rely on either.
The cause option
ES2022 added a second argument to the Error constructor. It is an options object, and its cause key holds the error that led to this one:
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Settings file is not valid JSON', { cause: err });
}
}
try {
parseSettings('{ "theme": ');
} catch (err) {
console.log(err.message); // 'Settings file is not valid JSON'
console.log(err.cause instanceof SyntaxError); // true
console.log(err.cause.message); // the original JSON.parse message
}The outer error describes the failed operation. The inner error, available as err.cause, keeps the technical details. Node.js 16.9+, Chrome 93+, Firefox 91+, and Safari 15+ support the option.
Passing cause through custom classes
Every built-in error type accepts the options object, including TypeError, RangeError, and AggregateError (where it is the third argument). Your own classes get the same support only if they forward the options to super:
class ConfigError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ConfigError';
}
}
const low = new SyntaxError('Unexpected end of JSON input');
const high = new ConfigError('Cannot read settings', { cause: low });
console.log(high.cause === low); // trueSeeing the cause in output
Node.js prints the cause when it logs an error. console.log(high) shows the ConfigError stack followed by a [cause]: SyntaxError: ... section. Recent browser consoles do the same. You get the full story without writing extra code.
What can be a cause
The cause value does not have to be an Error. Strings, objects, and other values are all accepted. In practice, pass the caught value as is. Code that reads err.cause should check instanceof Error before using .message or .stack. A later chapter covers the exact property rules.
Exercise
A class is defined as class DbError extends Error { constructor(msg, opts) { super(msg); this.name = 'DbError'; } }. What does new DbError('Query failed', { cause: new Error('timeout') }).cause return, and how do you fix it?
Show answer
It returns undefined because the options object is never passed to the Error constructor, so no cause property is created. Fix it by calling super(msg, opts).
Exercise
Rewrite catch (err) { throw new RangeError('Port out of range'); } so the original error is kept.
Show answer
catch (err) { throw new RangeError('Port out of range', { cause: err }); }. Built-in error types accept the same options object as Error.