← Back to Node.js, page 7

nodejs-0135 · Medium mid

How do you design consistent API errors with RFC 9457 problem details, and how do you version a Node.js REST API?

Return one error shape everywhere. RFC 9457 defines application/problem+json with type, title, status, detail and instance, plus your own fields such as errors. Map validation to 400 or 422, missing resources to 404, conflicts to 409 and unexpected failures to a generic 500 without internals. Version with a URL prefix (/v1) or a header, avoid breaking changes inside a version, and announce retirement with Deprecation and Sunset headers.

Full answer

Error format

  • Use the media type application/problem+json and these members: type (a URI that identifies the problem kind), title (short, stable), status (the HTTP status), detail (specific to this occurrence), instance (identifies this occurrence, for example the request id).
  • Add extension members: errors for field problems, code for a stable machine code, requestId.
  • Clients should switch on status and type or code, never parse the detail text.
  • Status codes: 400 malformed request, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 valid syntax but failed rules, 429 too many requests, 500 and 503 server side.
  • Never put stack traces, SQL or secret values in responses. Log them with the request id.
  • Keep one central error handler. Make 404 for unknown routes use the same format.

Versioning

  • URL prefix: /v1/users. Simple, visible, easy to route and cache. The most common choice.
  • Header or media type: Accept: application/vnd.school.v2+json, or a custom header. Cleaner URLs, harder to test and cache.
  • Prefer additive changes (new optional fields) inside a version. A breaking change (removed or renamed field, changed meaning) needs a new version.
  • Support old versions for a published period. Send Deprecation: true (or a date) and Sunset: <date> headers and a Link to the migration guide.
  • Share code between versions by putting the business logic in services and keeping versioned routers thin (mapping input and output).
javascript
const express = require('express');

class HttpProblem extends Error {
  constructor(status, title, detail, extra = {}) { super(detail); this.status = status; this.title = title; this.extra = extra; }
}

const app = express();
app.use(express.json());
let counter = 0;
app.use((req, res, next) => { res.locals.requestId = 'req-' + ++counter; next(); });

const v1 = express.Router();
v1.get('/students/:id', (req, res) => {
  if (req.params.id !== '1') throw new HttpProblem(404, 'Student not found', `No student with id ${req.params.id}`, { code: 'student_not_found' });
  res.set({ Deprecation: 'true', Sunset: 'Wed, 31 Dec 2026 23:59:59 GMT' }).json({ id: 1, name: 'Asha' }); // v1 is being retired
});
v1.post('/students', (req, res) => {
  if (!req.body.name) throw new HttpProblem(422, 'Validation failed', 'name is required', { code: 'validation_failed', errors: [{ field: 'name', message: 'required' }] });
  res.status(201).json({ id: 2, name: req.body.name });
});
const v2 = express.Router();
v2.get('/students/:id', (req, res) => res.json({ id: Number(req.params.id), fullName: 'Asha Rao' })); // renamed field: a breaking change

app.use('/v1', v1);
app.use('/v2', v2);
app.get('/crash', () => { throw new Error('password=secret in a SQL error'); });
app.use((req, res, next) => next(new HttpProblem(404, 'Route not found', `${req.method} ${req.path} does not exist`, { code: 'route_not_found' })));

app.use((err, req, res, next) => {
  const status = err.status || 500;
  const body = {
    type: 'https://example.com/problems/' + (err.extra?.code || 'internal-error'),
    title: err.status ? err.title : 'Internal Server Error',
    status,
    detail: err.status ? err.message : 'Something went wrong. Quote the request id to support.',
    instance: '/requests/' + res.locals.requestId,
    ...(err.extra || {}),
  };
  res.status(status).type('application/problem+json').json(body);
});

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const show = async (label, res) => console.log(label.padEnd(18), res.status, res.headers.get('content-type'), '\n   ', JSON.stringify(await res.json()));
  await show('v1 ok', await fetch(base + '/v1/students/1'));
  const deprecated = await fetch(base + '/v1/students/1');
  console.log('deprecation headers:', deprecated.headers.get('deprecation'), '|', deprecated.headers.get('sunset'));
  await show('v1 not found', await fetch(base + '/v1/students/9'));
  await show('v1 validation', await fetch(base + '/v1/students', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }));
  await show('v2 renamed field', await fetch(base + '/v2/students/1'));
  await show('unknown route', await fetch(base + '/nope'));
  await show('server error', await fetch(base + '/crash'));
  server.close();
});

The app serves two versions and returns every error as problem+json. The unexpected error is reported without the secret text from the exception. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): v1 ok 200 application/json; charset=utf-8 {"id":1,"name":"Asha"} deprecation headers: true | Wed, 31 Dec 2026 23:59:59 GMT v1 not found 404 application/problem+json; charset=utf-8 {"type":"https://example.com/problems/student_not_found","title":"Student not found","status":404,"detail":"No student with id 9","instance":"/requests/req-3","code":"student_not_found"} v1 validation 422 application/problem+json; charset=utf-8 {"type":"https://example.com/problems/validation_failed","title":"Validation failed","status":422,"detail":"name is required","instance":"/requests/req-4","code":"validation_failed","errors":[{"field":"name","message":"required"}]} v2 renamed field 200 application/json; charset=utf-8 {"id":1,"fullName":"Asha Rao"} unknown route 404 application/problem+json; charset=utf-8 {"type":"https://example.com/problems/route_not_found","title":"Route not found","status":404,"detail":"GET /nope does not exist","instance":"/requests/req-6","code":"route_not_found"} server error 500 application/problem+json; charset=utf-8 {"type":"https://example.com/problems/internal-error","title":"Internal Server Error","status":500,"detail":"Something went wrong. Quote the request id to support.","instance":"/requests/req-7"}

Key points

  • One error shape with type, title, status, detail, instance.
  • Clients use status and a stable code, not the detail text.
  • No internals in error responses.
  • URL versioning is simple, and breaking changes need a new version.
  • Deprecation and Sunset headers announce retirement.

Common mistakes

  • Different error shapes in different routes.
  • Sending 200 with an error message in the body.
  • Returning stack traces or SQL errors to clients.
  • Making breaking changes inside an existing version.
  • Parsing error messages on the client instead of using codes.

Follow-ups

  • Which status do you use for validation errors, 400 or 422?
  • How do you let clients migrate from v1 to v2?
  • How does a request id help with support?

Tips

  • Name the five problem members.
  • Say where internals go: into logs.
  • Mention Deprecation and Sunset.