Skip to main content

Overview

Hono provides robust error handling mechanisms to help you manage both expected and unexpected errors in your applications. Proper error handling ensures your API returns meaningful responses and maintains stability.

HTTPException

The HTTPException class is the primary way to throw HTTP errors in Hono. It allows you to return specific HTTP status codes with custom messages.

Basic Usage

HTTPException Options

The HTTPException constructor accepts:
  • status - HTTP status code (default: 500)
  • options.message - Error message
  • options.res - Custom Response object
  • options.cause - Original error cause

Custom Response

Return a custom Response object with the exception:

Global Error Handler

Define a custom error handler to catch all errors in your application:

Structured Error Responses

Return consistent error response structures:

NotFound Handler

Handle 404 errors with a custom not found handler:

Error Handling Middleware

Create middleware to handle errors for specific routes:

Validation Errors

Handle validation errors from the validator middleware:

Async Error Handling

Handle errors in async handlers:

Status Codes

Common HTTP status codes for errors:
  • 400 - Bad Request (validation errors)
  • 401 - Unauthorized (authentication required)
  • 403 - Forbidden (insufficient permissions)
  • 404 - Not Found (resource doesn’t exist)
  • 409 - Conflict (resource conflict)
  • 422 - Unprocessable Entity (semantic errors)
  • 429 - Too Many Requests (rate limiting)
  • 500 - Internal Server Error (server errors)
  • 503 - Service Unavailable (temporary issues)

Best Practices

Choose the correct HTTP status code that accurately represents the error condition.
Include clear, actionable error messages that help users understand what went wrong.
Always log errors server-side for debugging, but don’t expose internal details to clients.
Use a global error handler to ensure consistent error response format across your API.
Never include sensitive information like stack traces or internal paths in production error responses.