Error Handling
Learn how to implement consistent and informative error responses in your API design.
Error Response Structure
api.vision uses a consistent error response format to help clients understand and handle errors effectively:
{
"status": 404,
"error": "Not Found",
"message": "The requested resource was not found",
"path": "/users/999",
"timestamp": "2023-04-15T14:32:10Z"
}
The error response includes:
Field | Description |
---|---|
status | HTTP status code matching the response status |
error | Short name of the error type (usually matching the HTTP status phrase) |
message | Human-readable description of what went wrong |
path | The request path that generated the error |
timestamp | When the error occurred (ISO 8601 format) |
HTTP Status Codes
api.vision uses appropriate HTTP status codes to indicate the type of error:
Status Code | Name | Usage |
---|---|---|
400 | Bad Request | The request was malformed or invalid |
401 | Unauthorized | Authentication is required or was invalid |
403 | Forbidden | The user doesn't have permission for the requested action |
404 | Not Found | The requested resource doesn't exist |
405 | Method Not Allowed | The HTTP method is not supported for this resource |
409 | Conflict | The request conflicts with the current state of the resource |
422 | Unprocessable Entity | The request was well-formed but had semantic errors |
429 | Too Many Requests | The client has sent too many requests in a given time period |
500 | Internal Server Error | An unexpected error occurred on the server |
503 | Service Unavailable | The service is temporarily unavailable |
Validation Errors
For validation errors (status code 400 or 422), api.vision provides detailed validation information:
{
"status": 400,
"error": "Bad Request",
"message": "Validation failed",
"validationErrors": [
{
"field": "email",
"error": "must be a valid email address"
},
{
"field": "password",
"error": "must be at least 8 characters long"
},
{
"field": "age",
"error": "must be at least 18"
}
],
"path": "/users",
"timestamp": "2023-04-15T14:32:10Z"
}
The validationErrors
array contains objects with:
field
: The field that failed validationerror
: The specific validation error for that field
Error Codes
For more specific error identification, api.vision can include error codes:
{
"status": 400,
"error": "Bad Request",
"message": "Invalid API key format",
"code": "INVALID_API_KEY",
"path": "/users",
"timestamp": "2023-04-15T14:32:10Z"
}
Error codes are uppercase string identifiers that provide a stable way for clients to identify specific error conditions, regardless of the human-readable message.
Handling Partial Failures
For batch operations where some items succeeded and others failed, api.vision uses a more complex response structure:
{
"status": 207,
"message": "Multi-Status Response",
"results": [
{
"id": "item1",
"status": 200,
"result": { "id": 1, "name": "Updated Item 1" }
},
{
"id": "item2",
"status": 404,
"error": "Not Found",
"message": "Item with ID 'item2' does not exist"
},
{
"id": "item3",
"status": 400,
"error": "Bad Request",
"message": "Invalid data for item3",
"validationErrors": [
{ "field": "price", "error": "must be a positive number" }
]
}
],
"path": "/items/batch",
"timestamp": "2023-04-15T14:32:10Z"
}
Error Handling in Different Response Formats
api.vision maintains consistent error structures across different response formats:
JSON Format (Default)
// HTTP/1.1 404 Not Found
// Content-Type: application/json
{
"status": 404,
"error": "Not Found",
"message": "Resource with ID '123' not found",
"path": "/users/123",
"timestamp": "2023-04-15T14:32:10Z"
}
XML Format
// HTTP/1.1 404 Not Found
// Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8"?>
<error>
<status>404</status>
<error>Not Found</error>
<message>Resource with ID '123' not found</message>
<path>/users/123</path>
<timestamp>2023-04-15T14:32:10Z</timestamp>
</error>
Error Documentation
api.vision allows you to document possible errors for each endpoint:
{
"endpoints": {
"/users/:id": {
"get": {
"summary": "Get a user by ID",
"responses": {
"200": {
"description": "User found and returned successfully"
},
"404": {
"description": "User not found",
"example": {
"status": 404,
"error": "Not Found",
"message": "User with ID '123' not found",
"path": "/users/123",
"timestamp": "2023-04-15T14:32:10Z"
}
},
"401": {
"description": "Authentication required or invalid",
"example": {
"status": 401,
"error": "Unauthorized",
"message": "Authentication is required to access this resource",
"path": "/users/123",
"timestamp": "2023-04-15T14:32:10Z"
}
}
}
}
}
}
}
Custom Error Handling
api.vision allows you to customize error handling using interceptors:
{
"interceptors": {
"response": [
{
"name": "customErrorHandler",
"path": "**",
"script": "
// Skip if the response is not an error
if (res.status < 400) return res;
// Customize error format
const originalBody = res.body;
res.body = {
status: res.status,
error: utils.getHttpStatusText(res.status),
message: originalBody?.message || 'An error occurred',
errorId: utils.generateId(), // Add a unique error ID for tracking
path: req.path,
timestamp: new Date().toISOString(),
// Add link to documentation for this error
docs: `https://api.example.com/docs/errors/${res.status}`
};
// Log the error
console.error(`Error ${res.body.errorId}: ${res.status} ${res.body.message} at ${req.path}`);
return res;
"
}
]
}
}
Error Response Best Practices
Follow these best practices for effective error handling:
Use Appropriate Status Codes
Choose the most specific HTTP status code that accurately represents the error condition.
Provide Helpful Messages
Error messages should be clear, concise, and actionable. Explain what went wrong and possibly how to fix it.
Include Detailed Validation Errors
For validation failures, provide specific information about each invalid field rather than a general error.
Use Stable Error Codes
Include machine-readable error codes that remain stable even if error messages change.
Be Consistent
Use the same error format across all endpoints and error types to make client-side handling easier.
Avoid Exposing Sensitive Information
Don't include internal details, stack traces, or sensitive data in error responses.
Document Error Responses
Clearly document all possible error responses and codes in your API documentation.
Security Considerations
While error responses should be helpful, they should never expose sensitive information:
- Don't include internal paths or file names
- Don't return stack traces in production
- Don't expose database details or queries
- Don't reveal exact reasons for authentication failures
- Consider using generic messages for sensitive operations