Return Problem Details errors from API
Return errors from an HTTP API as Problem Details with the application/problem+json type, so every client reads the same fields.
Every API invents its own error body. RFC 9457 defines a standard one, called Problem Details, with a few fixed fields and a media type of its own.
import { createServer } from 'node:http';
const server = createServer((req, res) => {
const problem = {
type: 'https://example.com/problems/out-of-credit',
title: 'You do not have enough credit.',
status: 403,
detail: 'Your balance is 30, but the item costs 50.',
instance: '/account/12345/msgs/abc',
};
res.writeHead(problem.status, { 'Content-Type': 'application/problem+json' });
res.end(JSON.stringify(problem));
});
await new Promise((resolve) => server.listen(0, resolve));
const res = await fetch(`http://localhost:${server.address().port}/`);
console.log(res.status, res.headers.get('content-type'));
console.log(await res.json());
server.close();403 application/problem+json
{
type: 'https://example.com/problems/out-of-credit',
title: 'You do not have enough credit.',
status: 403,
detail: 'Your balance is 30, but the item costs 50.',
instance: '/account/12345/msgs/abc'
}type is a URI that identifies the kind of problem, title is the same for every occurrence of that kind, and detail explains this one. The status field repeats the HTTP status so the body is still useful after a proxy rewrites the response. See RFC 9457.
You can add your own members, such as a list of field errors for validation failures. Keep detail free of stack traces and internal names.