Error Handling Patterns
Error Categories
Recoverable Errors
Can be handled and recovered from.
File not found → Try alternate location
Network timeout → Retry with backoff
Unrecoverable Errors
Application cannot continue, must fail fast.
Out of memory
Invalid license key
Error Handling Patterns
Try-Catch-Finally
Traditional approach for exception handling.
try {
// risky operation
} catch (error) {
// handle error
} finally {
// cleanup
}
Result Type
Functional approach, error as return value.
const result = operation();
if (result.isError) {
// handle error
} else {
// use value
}
Callback with Error
Node.js convention.
fs.readFile('file.txt', (error, data) => {
if (error) {
// handle error
} else {
// use data
}
});
Retry Strategies
Exponential Backoff
Increase wait time between retries.
Wait 1s, then 2s, then 4s, then 8s...
Jitter
Add randomness to prevent thundering herd.
Wait (1s * random(0-1)) before retry
Circuit Breaker
Stop retrying after threshold failures.
3 failures → open circuit → fail fast
Best Practices
- Fail fast and clearly
- Log errors with context
- Don't swallow exceptions silently
- Use specific error types
- Provide meaningful error messages
- Implement proper cleanup
- Test error paths
- Monitor error rates and patterns
