principletypescriptMajor
Error Codes Catalog: Use machine-readable error codes alongside HTTP status codes
Viewed 0 times
error-codesstructured-errorsmachine-readablecatalogapi-errorsproblem-details
Problem
HTTP status codes are too coarse to communicate specific error conditions. A 400 could be a validation error, missing field, invalid format, or expired token — clients cannot distinguish these without parsing error messages, which are unstable.
Solution
Return a structured error body with a machine-readable code string alongside the HTTP status. Maintain a public error codes catalog (in docs or at /errors endpoint) mapping each code to its description, resolution steps, and related status code.
Why
Stable error codes allow clients to handle specific error conditions programmatically without parsing messages. They also make error handling logic portable across API versions.
Gotchas
- Error codes must be stable — treat them like public API. Renaming a code is a breaking change.
- Include a requestId in every error response to enable support lookups.
- Do not expose internal stack traces or database error messages in production error responses.
Code Snippets
Structured error response shape
// RFC 7807 Problem Details inspired
interface ApiError {
type: string // URI reference to error docs e.g. '/errors/VALIDATION_FAILED'
code: string // machine-readable e.g. 'VALIDATION_FAILED'
title: string // human-readable summary
detail?: string // specific instance description
requestId: string // for support lookup
errors?: Array<{ field: string; message: string }> // for validation
}
// Usage
res.status(422).json({
type: '/errors/VALIDATION_FAILED',
code: 'VALIDATION_FAILED',
title: 'Request validation failed',
detail: 'The email field is not a valid email address',
requestId: req.requestId,
errors: [{ field: 'email', message: 'Must be a valid email' }]
} satisfies ApiError)Revisions (0)
No revisions yet.