Typing Error Causes With ErrorOptions
Attach the underlying failure with ErrorOptions cause, then walk the cause chain to log root causes without losing the original stack.
Code
class ConfigError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ConfigError';
}
}
function parsePort(raw: string): number {
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new ConfigError('invalid port: ' + raw);
}
return port;
}
function loadConfig(raw: string): number {
try {
return parsePort(raw);
} catch (error) {
// cause 保留底层异常,外层只补充自己的上下文
throw new ConfigError('failed to load config', { cause: error });
}
}
try {
loadConfig('eighty');
} catch (error) {
let current: unknown = error;
while (current instanceof Error) {
console.log(current.name + ':', current.message);
current = current.cause;
}
console.log('root cause reached');
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
ConfigError: failed to load config
ConfigError: invalid port: eighty
root cause reachedHow the code works
The working surface is the class ConfigError and the functions parsePort and loadConfig — everything else is wiring.
The one repetition in this snippet is the loop while (current instanceof Error). Failure is loud: ConfigError aborts the current operation instead of degrading it.
Applying it
The primary signature is function parsePort(raw: string)
The demo output is labeled (root cause reached), so each line in the output traces back to its producing call.
Statements that matter
throw new ConfigError('failed to load config', { cause: error });
throw new ConfigError('invalid port: ' + raw);
return parsePort(raw);
Interactive Tools for This Topic
FAQ
- Does the code validate its input?
- The code throws `ConfigError`. Handle it at the call site or let it propagate deliberately.
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `parsePort`, `loadConfig` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.