Error Handling
Manage errors consistently across your Cortado backend using middleware, structured responses, and logging best practices.
Logging
Debugging
Error Handling Overview
In Cortado, error handling is designed to be predictable and centralized. By using middleware, you can catch exceptions thrown in any route handler or middleware function and respond with uniform error messages. This helps maintain a clean API contract and improves developer experience by avoiding unhandled crashes.
Errors can be thrown as JavaScript exceptions or returned as rejected promises. Cortado’s runtime ensures that errors bubble up through the middleware stack to a dedicated error handler.
Middleware for Error Management
The recommended approach is to define an error-handling middleware at the end of your middleware chain. This middleware catches any error passed down and formats the response appropriately.
Common error middleware tasks:
Logging error details for debugging
Returning standard error codes and messages
Differentiating between client errors (4xx) and server errors (5xx)
Masking sensitive information in production
You can also customize error responses based on the environment (development vs. production).
Error Response Structure
Consistent error responses make client-side handling easier. Cortado encourages returning JSON with clear fields such as:
error
: a short error code or typemessage
: a human-readable descriptiondetails
: optional extra info for debuggingstatus
: HTTP status code
This structured approach helps frontend apps present meaningful messages and decide on retries or alternative flows.
Logging and Monitoring
Integrating logging inside your error middleware is crucial for maintaining reliable applications. Cortado works well with common logging libraries like Winston or Pino.
Tips for effective logging:
Log error stacks only in development
Capture request context (headers, user info)
Use log levels (info, warn, error) appropriately
Forward critical errors to external monitoring services (Sentry, Datadog)
Handling Common Error Scenarios
Typical errors to handle explicitly include:
Authentication failures (401 Unauthorized)
Validation errors (400 Bad Request)
Resource not found (404 Not Found)
Rate limiting or throttling (429 Too Many Requests)
By catching these early in middleware, you ensure your API remains predictable and user-friendly.
Best Practices
Error handling should be part of your API design from day one. Some best practices in Cortado projects:
Always validate input and return early on failure
Use custom error classes to differentiate error types
Avoid exposing internal error details in production
Test error flows as thoroughly as success cases
With thoughtful error management, Cortado applications become robust, secure, and easier to maintain.
Last updated on
Jul 16, 2025