5 min read
ā¢Question 13 of 28mediumHow should you handle errors in APIs?
Best practices for API error handling.
What You'll Learn
- Error response structure
- Common error types
- Implementation patterns
Error Response Structure
code.jsJavaScript
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{ "field": "email", "message": "Invalid email format" },
{ "field": "password", "message": "Must be at least 8 characters" }
]
}
}Common Error Codes
| Status | Code | Description |
|---|---|---|
| 400 | BAD_REQUEST | Invalid request syntax |
| 401 | UNAUTHORIZED | Authentication required |
| 403 | FORBIDDEN | No permission |
| 404 | NOT_FOUND | Resource not found |
| 422 | VALIDATION_ERROR | Validation failed |
| 429 | RATE_LIMITED | Too many requests |
| 500 | INTERNAL_ERROR | Server error |
Implementation
code.jsJavaScript
// Custom error class
class ApiError extends Error {
constructor(statusCode, code, message, details = null) {
super(message);
this.statusCode = statusCode;
this.code = code;
this.details = details;
}
}
// Usage
throw new ApiError(404, 'NOT_FOUND', 'User not found');
// Error middleware
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
success: false,
error: {
code: err.code || 'INTERNAL_ERROR',
message: err.message,
details: err.details,
},
});
});