Skip to main content
Mizu simplifies error handling by letting you return errors directly from handlers. This keeps your code clean and ensures consistent error responses across your entire application.

Error Handling Philosophy

In Mizu, error handling follows a simple principle: handlers return errors, the framework handles them. This means:
  1. Your handlers focus on business logic
  2. Errors flow up naturally through return err
  3. One central error handler formats all responses
  4. Panics are caught and treated like errors
This approach eliminates scattered error handling code and ensures every error is logged and responded to appropriately.

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:
  1. Log the error with the request context
  2. Return a 500 Internal Server Error to the client
  3. Include a generic error message (no sensitive details exposed)

The ErrorHandler

Define a global error handler to customize how all errors are processed:
The error handler receives:
  • 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:
Example response:

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
While Mizu recovers from panics, you should still write defensive code. Panics are expensive and should be exceptions, not the norm.

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