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
TheHTTPException 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
TheHTTPException constructor accepts:
status- HTTP status code (default: 500)options.message- Error messageoptions.res- Custom Response objectoptions.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
Use appropriate status codes
Use appropriate status codes
Choose the correct HTTP status code that accurately represents the error condition.
Provide helpful error messages
Provide helpful error messages
Include clear, actionable error messages that help users understand what went wrong.
Log errors for debugging
Log errors for debugging
Always log errors server-side for debugging, but don’t expose internal details to clients.
Handle errors consistently
Handle errors consistently
Use a global error handler to ensure consistent error response format across your API.
Don't expose sensitive information
Don't expose sensitive information
Never include sensitive information like stack traces or internal paths in production error responses.
Related
- Validation - Validate input and handle validation errors
- Middleware - Create error handling middleware
- TypeScript - Type-safe error handling