javascript 54 lines · 8 steps

RFC 7807 problem details in Express

A custom error class and two middleware turn thrown errors into standardized application/problem+json responses.

Explained by highlit
1class ProblemError extends Error {
2 constructor(status, title, detail, extensions = {}) {
3 super(detail || title);
4 this.status = status;
5 this.title = title;
6 this.detail = detail;
7 this.extensions = extensions;
8 }
9}
10 
11function notFoundHandler(req, res, next) {
12 next(new ProblemError(404, 'Not Found', `No resource matches ${req.originalUrl}`, {
13 type: 'https://example.com/problems/resource-not-found',
14 }));
15}
16 
17function problemDetailsHandler(err, req, res, next) {
18 if (res.headersSent) return next(err);
19 
20 let problem;
21 if (err instanceof ProblemError) {
22 problem = {
23 type: err.extensions.type || 'about:blank',
24 title: err.title,
25 status: err.status,
26 detail: err.detail,
27 ...err.extensions,
28 };
29 } else if (err.name === 'ValidationError' && err.errors) {
30 problem = {
31 type: 'https://example.com/problems/validation-error',
32 title: 'Your request parameters did not validate',
33 status: 422,
34 errors: Object.values(err.errors).map((e) => ({ field: e.path, message: e.message })),
35 };
36 } else {
37 req.log?.error({ err }, 'unhandled error');
38 problem = {
39 type: 'about:blank',
40 title: 'Internal Server Error',
41 status: 500,
42 };
43 }
44 
45 delete problem.extensions;
46 problem.instance = req.originalUrl;
47 
48 res
49 .status(problem.status)
50 .type('application/problem+json')
51 .json(problem);
52}
53 
54module.exports = { ProblemError, notFoundHandler, problemDetailsHandler };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A dedicated Error subclass lets you carry HTTP status and structured metadata alongside the message.
  2. 2Express recognizes a middleware with four arguments as an error handler, funneling every next(err) into it.
  3. 3Normalizing all failures into one response shape gives API clients a consistent contract for errors.

Related explainers

Share this explainer

Here's the card — post it anywhere.

RFC 7807 problem details in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code