Lesson 9: Error Handling with Grace
How your software fails dictates the vibe experienced by both the user and the developer debugging the issue. Bad Vibe error handling means silent failures, vague messages, or crashing the entire application.
The Vibe of Exceptions
Exceptions (errors/panics) are control flow mechanisms. They should be used to signal unexpected or unrecoverable conditions, not standard business logic.
Principle 1: Fail Early, Fail Loudly
If you detect a condition that prevents proper execution (e.g., a null parameter where one is required), throw an informative error immediately. Don't let the bad data propagate deep into the system.
java // Bad Vibe: Allows Null to cause problems later public User getUser(String userId) { // ... returns null if not found return db.fetch(userId); }
// Good Vibe: Explicitly handles failure state at the boundary public User findUser(String userId) { if (userId == null || userId.isEmpty()) { throw new IllegalArgumentException("User ID cannot be empty."); } // ... }
Principle 2: Informative Error Messages
Error messages are documentation for failure. They should provide enough context for the developer to understand:
- What happened.
- Where it happened (file/function).
- Why it happened (if possible).
Handling Errors at the Boundary
Catch errors at the boundary layer (e.g., the API handler or UI) and transform the raw, technical error into a polished, user-friendly message (for UX) or a structured log entry (for DX).
- User Vibe: 'Payment failed due to invalid card details.' (Friendly)
- Developer Vibe (Log): 'Stripe API returned 402 (Insufficient Funds). Request ID: req_abc123'