Error Handling Philosophy
In Mizu, error handling follows a simple principle: handlers return errors, the framework handles them. This means:- Your handlers focus on business logic
- Errors flow up naturally through
return err - One central error handler formats all responses
- Panics are caught and treated like errors
Returning Errors from Handlers
Any handler can return an error to indicate something went wrong:Default Behavior
If you donβt configure a custom error handler, Mizu will:- Log the error with the request context
- Return a
500 Internal Server Errorto the client - Include a generic error message (no sensitive details exposed)
The ErrorHandler
Define a global error handler to customize how all errors are processed:c- The request context (same as handlers)err- The error returned from the handler
The error handler should always send a response. If it doesnβt, the client will receive an empty response.
Custom Error Types
Create custom error types to carry additional information like HTTP status codes:Defining Custom Errors
Using Custom Errors in Handlers
Handling Custom Errors
HTTP Error Responses
RFC 7807 Problem Details
For production APIs, consider using the RFC 7807 problem details format:Different Response Formats
Serve different error formats based on client expectations:Error Wrapping with Context
Use Goβs error wrapping to add context as errors bubble up:Unwrapping in Error Handler
Panic Recovery
Mizu automatically recovers from panics and converts them to errors. This prevents your server from crashing:Handling Panics
Panics are wrapped in*mizu.PanicError:
When Panics Occur
Common causes of panics:- Nil pointer dereference
- Index out of bounds
- Type assertion failure
- Divide by zero
Error Logging
Log Levels by Error Type
Including Request Context
Error Monitoring Integration
Sending to Sentry
Custom Metrics
Testing Error Scenarios
Testing Error Responses
Testing Panic Recovery
Testing Custom Error Types
Complete Example
Hereβs a complete example with custom errors, error handler, and multiple routes:Best Practices
Do
Donβt
Summary
Whatβs Next
- Middleware - Error handling in middleware
- Logging - Structured logging for errors
- Context - Request context and cancellation
- Response - Sending error responses