Part 4: Functional Error Handling - Railway-Oriented Programming
Introduction
The Problem with Exceptions
// Exception-based approach - problems!
function parseUser(json: string): User {
try {
const data = JSON.parse(json); // Might throw
if (!data.username) {
throw new Error('Missing username');
}
if (!data.email) {
throw new Error('Missing email');
}
return {
username: data.username,
email: data.email
};
} catch (error) {
// Lost type information
throw new Error(`Parse error: ${error}`);
}
}
function processUser(json: string): void {
try {
const user = parseUser(json); // Might throw, but type doesn't say so!
saveUser(user); // Might throw too!
sendEmail(user.email); // And this!
} catch (error) {
// Which function threw? What error type?
console.error('Something failed:', error);
}
}Either/Result Type
Option/Maybe Type
Mapping Over Either
FlatMap/Chain for Either
Real Example: User Registration
Railway-Oriented Programming
Real Example: API Request Processing
Option Helpers
Real Example: Database Query
Combining Multiple Results
Best Practices
1. Make Errors Explicit in Types
2. Use Option for Nullable Values
3. Compose Error Handling
What's Next
PreviousPart 3: Closures and Currying - Function FactoriesNextPart 5: Advanced Functional Patterns - Production-Ready Systems
Last updated