The Problem with Throwing Errors
Why exceptions hide failure from the type system.
Exceptions Are Invisible
When a function throws, its signature does not say so. The type system cannot see which functions may fail, so callers have no compiler nudge to handle errors.
A Throwing Function
This function looks like it always returns a number, but it can throw. The return type number hides the failure case completely.
function parsePort(s: string): number {
const n = Number(s);
if (Number.isNaN(n)) throw new Error("bad port");
return n;
}
console.log(parsePort("8080")); // 8080All lessons in this course
- The Problem with Throwing Errors
- Modeling Result Types
- Option and Maybe Types
- Railway-Oriented Programming