patterntypescriptexpressModerate
RFC 7807 Problem Details: Structured Error Responses
Viewed 0 times
RFC 7807problem detailserror responseapplication/problem+jsonAPI errors
Problem
API errors return inconsistent formats — sometimes a string, sometimes {error: '...'}, sometimes {message: '...', code: N}. Clients need to write different parsers for each error shape.
Solution
Implement RFC 7807 Problem Details format for consistent, machine-readable errors.
interface ProblemDetails {
type: string; // URI identifying the problem type
title: string; // Short human-readable summary
status: number; // HTTP status code
detail?: string; // Specific explanation for this occurrence
instance?: string; // URI of the specific occurrence
[key: string]: unknown; // Extension members
}
// Express middleware
function problemDetails(
err: AppError,
req: Request,
res: Response,
next: NextFunction
) {
res.status(err.status).json({
type: `https://api.example.com/errors/${err.code}`,
title: err.title,
status: err.status,
detail: err.message,
instance: req.path,
} satisfies ProblemDetails);
}
// Content-Type must be application/problem+json
res.setHeader('Content-Type', 'application/problem+json');Why
RFC 7807 provides a standard error format for HTTP APIs. Clients can identify problem types by URI, display appropriate messages, and handle specific error codes programmatically.
Gotchas
- The Content-Type must be 'application/problem+json', not 'application/json'.
- The 'type' field should be an absolute URI pointing to documentation for the error type.
- Never include stack traces in production error responses — log them server-side only.
Revisions (0)
No revisions yet.