Unknown Errors and Result Types
In a catch clause, treat the caught value as unknown: JavaScript permits throwing strings, objects, and other values, not only Error instances. Narrow the value before reading message. For expected failures, a discriminated Result type can make success and failure explicit and force callers to handle both.
Exceptions remain useful for exceptional or infrastructure failures. A Result union can be better for expected domain outcomes such as validation failures. Choose one convention per boundary and document how callers should handle failures.
Narrow a caught error
try {
await saveDocument();
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
} else {
console.error("Unknown failure", error);
}
}💡 The
instanceof Error check narrows the unknown value before accessing message. A catch handler should not assume all thrown values are standard Error instances.Key Takeaways
- Catch values should be treated as unknown.
- Narrow before accessing error-specific properties.
- Use Result unions for expected failures when explicit handling helps.
Knowledge Check
Why should a caught value be treated as `unknown`?