Requests, Responses and Data · Lesson 8 of 30
REST API Error Handling with Problem Details
On this page
Errors are part of your API's contract. A client needs to know what went wrong, which field caused it, and whether retrying helps – in a format it can handle without special cases for every endpoint. Instead of inventing your own shape, use the IETF standard: Problem Details for HTTP APIs (RFC 9457), served as application/problem+json.
In this lesson
- The problem details format
- Field-level validation errors
- One error handler for the whole API
- Never leak stack traces
The format
| Member | Meaning |
|---|---|
type | a URI identifying the kind of problem (can link to docs) |
title | a short, human-readable summary of that kind |
status | the HTTP status code, repeated for convenience |
detail | an explanation of this occurrence |
instance | the request path or an id for this occurrence |
| extensions | your own fields: errors, code, requestId… |
A consistent error system
// server.js
import express from 'express';
const app = express();
app.use(express.json());
// One error type for expected problems
class ApiError extends Error {
constructor(status, type, title, detail, extra = {}) {
super(detail);
Object.assign(this, { status, type, title, extra });
}
}
const stock = { pen: 10, notebook: 0 };
app.post('/api/orders', (req, res) => {
const { sku, quantity } = req.body ?? {};
const errors = [];
if (typeof sku !== 'string') errors.push({ field: 'sku', message: 'is required' });
if (!Number.isInteger(quantity) || quantity < 1) errors.push({ field: 'quantity', message: 'must be a whole number of at least 1' });
if (errors.length) throw new ApiError(422, 'validation-error', 'Your request has invalid fields', `${errors.length} field(s) need attention`, { errors });
if (!(sku in stock)) throw new ApiError(404, 'product-not-found', 'Product not found', `No product with SKU '${sku}'`);
if (stock[sku] < quantity) {
throw new ApiError(409, 'out-of-stock', 'Not enough stock', `Only ${stock[sku]} of '${sku}' left`, { available: stock[sku] });
}
res.status(201).json({ id: 'ord_1001', sku, quantity });
});
app.get('/api/crash', () => {
throw new Error('db connection string: postgres://admin:secret@10.0.0.5'); // an unexpected bug
});
// 404 for unknown routes
app.use((req, res, next) => next(new ApiError(404, 'route-not-found', 'Not found', `${req.method} ${req.path} does not exist`)));
// The single place where errors become responses
app.use((err, req, res, next) => {
const known = err instanceof ApiError;
if (err.type === 'entity.parse.failed') { // broken JSON from express.json()
err = new ApiError(400, 'malformed-json', 'Malformed JSON', 'The request body is not valid JSON');
} else if (!known) {
console.error('Unexpected error:', err.message); // log details on the server only
err = new ApiError(500, 'internal-error', 'Something went wrong', 'An unexpected error occurred. Please try again later.');
}
res.status(err.status).type('application/problem+json').json({
type: `https://api.learnfrenzy.com/problems/${err.type}`,
title: err.title,
status: err.status,
detail: err.message,
instance: req.originalUrl,
...err.extra,
});
});
app.listen(process.env.PORT ?? 3000);
$ curl -X POST http://localhost:3000/api/orders -H 'Content-Type: application/json' -d '{"quantity":0}'
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.learnfrenzy.com/problems/validation-error",
"title": "Your request has invalid fields",
"status": 422,
"detail": "2 field(s) need attention",
"instance": "/api/orders",
"errors": [
{
"field": "sku",
"message": "is required"
},
{
"field": "quantity",
"message": "must be a whole number of at least 1"
}
]
}
$ curl -X POST http://localhost:3000/api/orders -H 'Content-Type: application/json' -d '{"sku":"notebook","quantity":2}'
HTTP/1.1 409 Conflict
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.learnfrenzy.com/problems/out-of-stock",
"title": "Not enough stock",
"status": 409,
"detail": "Only 0 of 'notebook' left",
"instance": "/api/orders",
"available": 0
}
$ curl -X POST http://localhost:3000/api/orders -H 'Content-Type: application/json' -d '{"sku": pen}'
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.learnfrenzy.com/problems/malformed-json",
"title": "Malformed JSON",
"status": 400,
"detail": "The request body is not valid JSON",
"instance": "/api/orders"
}
$ curl http://localhost:3000/api/crash
HTTP/1.1 500 Internal Server Error
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.learnfrenzy.com/problems/internal-error",
"title": "Something went wrong",
"status": 500,
"detail": "An unexpected error occurred. Please try again later.",
"instance": "/api/crash"
}
$ curl http://localhost:3000/api/unknown
HTTP/1.1 404 Not Found
Content-Type: application/problem+json; charset=utf-8
{
"type": "https://api.learnfrenzy.com/problems/route-not-found",
"title": "Not found",
"status": 404,
"detail": "GET /api/unknown does not exist",
"instance": "/api/unknown"
}
Server log:
Unexpected error: db connection string: postgres://admin:secret@10.0.0.5Where errors go
- Expected problema route throws ApiError with a status, type and details
- Unknown route or broken JSONturned into ApiError by the 404 handler or the parser check
- Unexpected buglogged in full on the server, replaced by a generic 500
- Error middlewareformats every one of them as application/problem+json
- Validation errors list every invalid field at once, so a form can highlight them all.
- The
typeis stable; clients branch on it (or on your owncodefield), never on the human-readable text. - The crash leaked nothing: the database URL went to the server log only. Stack traces and internal messages in responses are a classic security finding.
- Express 5 forwards errors thrown in route handlers – including in
asynchandlers – to the error middleware automatically.
Practice
Try it yourself
Add a
requestIdto every problem response, read from anX-Request-Idrequest header (or"unknown").Show solution
// server.js import express from 'express'; const app = express(); app.get('/api/items/:id', (req, res) => { res.status(404).type('application/problem+json').json({ type: 'https://api.learnfrenzy.com/problems/item-not-found', title: 'Item not found', status: 404, detail: `No item with id ${req.params.id}`, requestId: req.get('X-Request-Id') ?? 'unknown', }); }); app.listen(process.env.PORT ?? 3000);$ curl http://localhost:3000/api/items/99 -H 'X-Request-Id: req_7f3a' HTTP/1.1 404 Not Found Content-Type: application/problem+json; charset=utf-8 { "type": "https://api.learnfrenzy.com/problems/item-not-found", "title": "Item not found", "status": 404, "detail": "No item with id 99", "requestId": "req_7f3a" }
Quick check
What media type do problem details use?
application/problem+json.
Should clients branch on detail text?
No – use the stable type (or an error code); detail is for humans.
What should a 500 response contain?
A generic message and maybe a request id – never stack traces or internal details.
Summary
- Use RFC 9457 problem details: type, title, status, detail, instance, plus your extensions.
- Report all validation errors per field; give each problem kind a stable type.
- Handle errors in one middleware; log internals, return safe messages.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.