Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

problem.jsJavaScript
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();
Text
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.

Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.