Overview
Result Handlers are responsible for transforming endpoint outputs and errors into HTTP responses. They ensure consistent response formatting across your API and handle both successful results and errors. Every endpoint uses a Result Handler, either the default one or a custom implementation.Result Handler Structure
A Result Handler defines:- Positive response schema: How successful outputs are formatted
- Negative response schema: How errors are formatted
- Handler function: Logic that sends the actual HTTP response
The Default Result Handler
ThedefaultResultHandler provides a standard response format:
- 200 for successful responses
- 400 for input validation errors
- 500 for server errors (or error’s
statusCodeif usingcreateHttpError)
Creating Custom Result Handlers
Handler Function Parameters
The handler receives a discriminated union based on success or failure:Error | null
The error if one occurred, or
null on success. Use ensureHttpError() to normalize it.FlatObject | null
The validated endpoint output on success, or
null if an error occurred.FlatObject | null
The validated input. Can be
null if the error occurred before input validation.FlatObject
Context from middlewares. May be incomplete if middleware execution was interrupted.
Request
Express request object with full access to headers, cookies, etc.
Response
Express response object for sending the response.
ActualLogger
Configured logger instance for recording errors.
Using Custom Result Handlers
Create an EndpointsFactory with your Result Handler:Response Schemas
Static Schemas
Define a fixed response structure:Dynamic Schemas (Lazy)
Generate the schema based on the endpoint’s output schema:Using lazy schemas (functions) allows the documentation generator to know the exact response structure for each endpoint.
Different Status Codes
Customize status codes for different scenarios:Non-JSON Responses
Plain Text
File Downloads
Empty Responses
For 204 No Content or redirects:Error Handling
Normalizing Errors
UseensureHttpError() to convert any error to an HTTP error:
InputValidationError→ 400 Bad RequestOutputValidationError→ 500 Internal Server ErrorHttpError→ Uses error’sstatusCode- Other errors → 500 Internal Server Error
Logging Errors
UselogServerError() helper to log server-side errors:
Public vs Private Error Messages
Control which error messages are exposed to clients:Resource Cleanup
Clean up resources like database connections in the Result Handler:Common Patterns
Standard REST API
GraphQL-style Responses
API with Metadata
Array Result Handler (Legacy)
Best Practices
See Also
- Endpoints - Create endpoints that use Result Handlers
- Error Handling - Error types and handling strategies
- Context - Clean up context resources in handlers