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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A dedicated Error subclass lets you carry HTTP status and structured metadata alongside the message.
- 2Express recognizes a middleware with four arguments as an error handler, funneling every next(err) into it.
- 3Normalizing all failures into one response shape gives API clients a consistent contract for errors.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/rfc-7807-problem-details-in-express-explained-javascript-a6b5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.