--- name: error-handling description: Design robust error handling — error classification, propagation, context wrapping with thiserror/anyhow, user-facing messages, panic vs recoverable, Go/Rust/general patterns. license: MIT --- ## What I do Guide error handling design. Use when handling errors, designing error types, or improving error messages. ## Error Classification ### By Type - Validation: Invalid input - e.g., missing required field - Not Found: Resource doesn't exist - e.g., user not found - Conflict: State conflict - e.g., duplicate record - Permission: Not authorized - e.g., not allowed to access - External: Service failure - e.g., database timeout - Internal: Unexpected bug - e.g., null pointer ### By Recovery - Retryable: Yes - retry automatically - Timeout: Maybe - suggest retry - Fatal: No - log, show generic message ### Recoverable vs Unrecoverable **Recoverable Errors:** - Network timeouts - Missing files - Invalid user input - API rate limits **Unrecoverable Errors:** - Out of memory - Stack overflow - Programming bugs (null pointer, etc.) ## Error Handling Philosophies ### Exceptions vs Result Types - **Exceptions**: Traditional try-catch, disrupts control flow - **Result Types**: Explicit success/failure, functional approach - **Error Codes**: C-style, requires discipline - **Option/Maybe Types**: For nullable values **When to Use Each:** - Exceptions: Unexpected errors, exceptional conditions - Result Types: Expected errors, validation failures - Panics/Crashes: Unrecoverable errors, programming bugs ## Error Propagation ### Best Practices - Return early on errors - Don't swallow errors silently - Add context when propagating - Preserve error information - **Log all branches** - include request IDs for tracing - **Include correlation IDs** - trace requests across services ### Example ```python # Bad: Loses context try: user = get_user(user_id) except Exception as e: logger.error("Error") return None # Good: Preserve and add context try: user = get_user(user_id) except DatabaseError as e: logger.error("Failed to get user", extra={"user_id": user_id, "error": str(e)}) raise UserServiceError(f"Cannot retrieve user {user_id}") from e ``` ## User-Facing Errors ### Do - Use plain language - Tell user what happened and what to do - Be apologetic but not excessive ### Don't - Show stack traces, internal error codes - Blame the user - Leak sensitive information ### Good Error Message Template ``` [What happened]: We couldn't save your document. [Why]: The filename contains characters we don't support. [Action]: Please rename your file using only letters, numbers, and dashes. ``` ### Internal vs External **Internal (logs)**: - Stack traces - Error codes (ERR_001) - Technical details **External (users)**: - Friendly explanation - What to do next - Plain language ## Logging ### Log - Error type and message - Stack trace (unexpected errors) - Context (user ID, request ID) - Timestamp ### Don't Log - Passwords, tokens - Sensitive user data ```python logger.error( "Failed to process order", extra={"order_id": order.id, "user_id": order.user_id, "error_type": type(e).__name__}, exc_info=True ) ``` ## Graceful Degradation - Fallback to cached data - Show partial results - Disable non-critical features - Queue for later retry ## Circuit Breaker - Closed: Normal operation, failures counted - Open: Fail fast, don't call service - Half-open: Allow test requests ### Circuit Breaker States ``` CLOSED → Normal operation, track failures OPEN → Too many failures, reject requests immediately HALF_OPEN → Test if service recovered ``` ### Implementation Concept ``` function callWithCircuitBreaker(func): if state == OPEN: if timeSinceLastFailure > timeout: state = HALF_OPEN else: raise CircuitOpenError try: result = func() onSuccess() return result except: onFailure() raise ``` ## Error Aggregation Collect multiple errors instead of failing on first error. **Use when:** Validating multiple fields, batch processing, collecting all issues before reporting. ``` class ErrorCollector: errors = [] add(error): errors.push(error) hasErrors(): return errors.length > 0 throw(): if errors.length == 1: throw errors[0] throw AggregateError(errors, "N errors occurred") ``` **Example: Validate multiple fields** ``` function validateUser(data): errors = ErrorCollector() if not data.email: errors.add("Email is required") if not data.name: errors.add("Name is required") if errors.hasErrors(): errors.throw() return data ``` --- ## Retry Patterns ### Exponential Backoff Wait longer between each retry attempt. ``` retry(attempts=3, backoff=2): for i in range(attempts): try: return func() except: if i < attempts - 1: sleep(backoff ^ i) # 1s, 2s, 4s... else: raise ``` --- ## Best Practices 1. **Fail Fast**: Validate input early, fail quickly 2. **Preserve Context**: Include stack traces, metadata, timestamps 3. **Meaningful Messages**: Explain what happened and how to fix it 4. **Log Appropriately**: Error = log, expected failure = don't spam logs 5. **Handle at Right Level**: Catch where you can meaningfully handle 6. **Clean Up Resources**: Use try-finally, context managers, defer 7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore 8. **Type-Safe Errors**: Use typed errors when possible --- ## Common Pitfalls - **Catching Too Broadly**: `except Exception` hides bugs - **Empty Catch Blocks**: Silently swallowing errors - **Logging and Re-throwing**: Creates duplicate log entries - **Not Cleaning Up**: Forgetting to close files, connections - **Poor Error Messages**: "Error occurred" is not helpful - **Returning Error Codes**: Use exceptions or Result types - **Ignoring Async Errors**: Unhandled promise rejections --- ## Anti-Patterns ### Empty Catch ```python # Bad try: do_something() except: pass # Good try: do_something() except SpecificError: handle_gracefully() ``` ### Catching Too Broad ```python # Bad: catches everything including KeyboardInterrupt try: do_something() except Exception: pass # Good try: do_something() except ValueError: handle_validation_error() except TimeoutError: handle_timeout() ``` --- ## Advanced: Eliminate Error Cases ### The Core Principle Don't treat errors as special. Structure code so errors flow through the same codepaths as normal cases. Fewer codepaths = fewer bugs. ### Zero-Is-Initialization If zero initialization is valid for your data type, let failures produce zero instead of errors. ```rust // Zero means empty string - no error handling needed struct String8 { ptr: *const u8, len: usize } // A zero-initialized String8 is naturally an empty string ``` ```rust // Instead of: Result fn get_user_name(user: &User) -> String8 { user.name // Returns zero if no name - caller works seamlessly } ``` ### Fail Early Allocate resources upfront. Fail before doing work, not after. ```rust // Bad: Fail deep in call stack fn process_data(data: &Data) -> Result { let buffer = allocate_large_buffer()?; // Might fail here transform(&mut buffer, data)?; // Too late! } // Good: Fail early, guarantee success downstream fn process_data(data: &Data) -> Result { let buffer = allocate_large_buffer()?; // Fail HERE first transform(&mut buffer, data); // Now guaranteed success } ``` ### Prefer AND Over OR Return error info IN ADDITION TO result, not instead of. ```rust // OR: Either valid data OR error (bifurcates caller's codepath) fn parse(text: &str) -> Result { match parse(text) { Ok(ast) => process(ast), Err(e) => handle_error(e), // Separate codepath! } } // AND: Error info alongside result (single codepath) struct ParseResult { value: T, errors: Vec, } fn parse(text: &str) -> ParseResult { // Always returns valid result - errors are ADDITIONAL info } ``` ### Nil Structs (Guaranteed Valid Reads) Return pointers to nil structs instead of null pointers. ```c // Nil struct - reading any field is safe Node nil_node = { .first = &nil_node, .last = &nil_node, .value = 0 }; // Returns &nil_node on failure - guaranteed valid reads Node *n1 = ChildFromValue(root, 1); Node *n2 = ChildFromValue(n1, 2); // No null checks needed ``` --- Use this skill when designing error handling or improving error messages.