What is a consistent REST API error format, and why isn't the HTTP status enough?
A consistent REST API error format is a single, documented response shape that every service returns when a request fails. It carries a stable, machine-readable error code alongside the HTTP status and a human-readable message.
The status alone is too coarse. A 409 Conflict from an orders service might mean the order was already submitted, the inventory version changed, or the coupon was already redeemed. Each of those needs different client behavior: show a confirmation, retry with fresh data, or remove the coupon. Clients can't branch on a status that covers all three. Many teams fall back to matching on the message text, and that breaks the first time someone rewords a sentence or adds a translation. The code has to be the contract, and the message should stay free to change.
This guide treats consistency as a property of shared infrastructure, not team discipline. You get it from three things: a versioned catalog of error codes, a response body built on Problem Details (RFC 9457), and one error-handling boundary per service that turns every failure into that shape. You don't get it by letting each team choose statuses and messages on its own.
The payoff is largest for backend and platform engineers running several Node.js services behind shared client SDKs or an API gateway. That's where inconsistent errors pile up into special-case parsing. For a single small service with one internal consumer, a full catalog is probably overkill. A few well-chosen statuses and clear messages will usually do.
Who should use a shared error contract?
The approach fits these roles and situations:
- Platform and backend engineers who own several Node.js services. They maintain the catalog package and the error boundary, and they gain the most from removing per-service differences.
- Teams that build client SDKs, web frontends or mobile apps against those services. They write the branching logic that depends on stable codes. A shared contract lets them write one error handler instead of one per service.
- Teams that run an API gateway or a public API. The gateway is where internal errors get translated for external consumers, and translation only works if the internal codes are predictable.
- On-call engineers and SREs. A shared shape with a request ID in every error lets them move from a client report to the matching log entry without knowing which service produced it.
It fits less well for a single service with one consumer that the same team owns. In that case the team can change both sides together, so the catalog, the package and the CI checks add overhead without removing much coordination.
When should you adopt it?
Adopt a shared error contract when one or more of these conditions apply:
- More than one service returns errors to the same client. As soon as a frontend or SDK talks to two services, any difference in error shape becomes client-side special casing.
- Clients need to act differently on failures that share a status. If a
409or400can mean several things that need different UI or retry behavior, you need codes. - Client code matches on message strings. That is a sign the contract is missing, and it is fragile to rewording and translation.
- You are building a new API or a new major version. It costs least to adopt the format before clients depend on an older shape.
- You are adding a gateway, a public API or third-party consumers. External clients upgrade slowly, so the error contract has to be stable before they arrive.
Defer it when you have one service and one client owned by the same team, or when the API is a short-lived internal prototype. In those cases, clear HTTP statuses and readable messages are enough, and you can add the catalog later through the migration strategies described at the end of this guide.
How does it work end to end?
The design has four parts that run in the same order on every failed request:
- A catalog defines the codes. A shared package maps each code, such as
PAYMENT_CARD_DECLINED, to one HTTP status, onetypeURI and one default title. This is the single source of truth. - Services throw catalog errors. Route handlers and domain code throw an error class that takes a catalog key, for example
new AppError('PAYMENT_CARD_DECLINED', { detail }). They never set the status or build a response body themselves. - One error boundary per service builds the response. An Express error-handling middleware, registered last, catches everything passed to
next(err)or thrown in wrapped handlers. It maps known errors through the catalog, converts parser and routing failures to their catalog codes, hides unknown errors behind a generic 500, logs the full error with the request ID, and sends anapplication/problem+jsonbody. - Clients branch on
codeand fall back on status. Consumers switch on known codes. When they see a code they don't recognize, they handle it by status class, so a newer service adding a code never breaks an older client.
Between services, each hop wraps or translates downstream codes and forwards the request ID unchanged. Contract tests and CI checks make sure no service bypasses the boundary. The sections below cover each part in detail.
How does the Problem Details format (RFC 9457) work?
RFC 9457 obsoletes RFC 7807 and defines a standard error body served as application/problem+json. Because the format is standard, generic clients and gateways can recognise an error without knowing anything about your service.
The standard members
type: a URI reference that identifies the problem type. It is the primary identifier. When omitted, it defaults toabout:blank.title: a short summary of the problem type. It should not change from one occurrence to the next.status: the HTTP status code. It is advisory and should match the actual response status, because intermediaries can rewrite the response.detail: a human-readable explanation of this specific occurrence. Clients should not parse it.instance: a URI reference that identifies this specific occurrence.
Extension members
The RFC allows extra members and requires consumers to ignore any they don't understand. That rule is why you can add these without breaking existing clients:
- a stable
codesuch asORDER_ALREADY_SHIPPED - a
traceIdfor correlating logs - an
errorsarray of{ field, code, message }objects for validation failures
Choosing type URIs
A type URI that resolves to a documentation page helps consumers, but each page has to be written and kept accurate. A URI that looks like a link but returns 404 confuses consumers more than having no page at all.
Two choices are legitimate:
- Use
about:blankand rely oncode. In that case,titleshould be the HTTP status phrase. - Use URIs that are deliberately non-resolving, such as
tag:URIs, which serve as identifiers only.
Alternatives
| Approach | Standard media type | Multiple errors | Generic tooling |
|---|---|---|---|
| Problem Details | Yes | Via extension | Recognisable |
| Ad-hoc JSON | No | Varies | None |
JSON:API errors array |
Yes, if you adopt JSON:API | Native | Within JSON:API only |
| Custom envelope | No | Your choice | Only your own |
const express = require('express');
const { randomUUID } = require('node:crypto');
class ProblemError extends Error {
constructor({ status, code, title, detail, type = 'about:blank', errors }) {
super(detail);
Object.assign(this, { status, code, title, detail, type, errors });
}
}
const app = express();
app.post('/orders/:id/cancel', (req, res) => {
// Non-resolving tag: URI that works purely as an identifier, plus a stable code clients can switch on.
throw new ProblemError({
status: 409,
type: 'tag:example.com,2024:problems/order-already-shipped',
title: 'Order already shipped',
code: 'ORDER_ALREADY_SHIPPED',
detail: `Order ${req.params.id} shipped and can no longer be cancelled.`,
});
});
// Central error handler, so every service emits the same shape.
app.use((err, req, res, next) => {
const known = err instanceof ProblemError;
const status = known ? err.status : 500;
const body = {
// With about:blank, title should be the HTTP status phrase.
type: known ? err.type : 'about:blank',
title: known ? err.title : 'Internal Server Error',
status, // Keep in sync with the real response status.
detail: known ? err.detail : undefined, // Never leak internals for unknown errors.
instance: req.originalUrl,
code: known ? err.code : 'INTERNAL_ERROR', // Extension member.
traceId: req.get('x-request-id') || randomUUID(), // Extension member.
errors: known ? err.errors : undefined, // Optional [{ field, code, message }].
};
// Set the media type before res.json, which keeps an existing Content-Type.
res.status(status).type('application/problem+json').json(body);
});
app.listen(3000);
An Express error handler that turns thrown errors into RFC 9457 application/problem+json responses. Each response carries the standard members plus code, traceId and errors extension members, and the type is either a non-resolving tag: URI or about:blank.
How should you design an error code catalog?
Each code follows one convention: a namespace for the owning domain, then a specific condition, in SCREAMING_SNAKE_CASE, for example PAYMENT_CARD_DECLINED. The namespace prevents collisions when several teams add codes independently, and it shows a reader which service owns the failure. Every code maps to exactly one type URI and the reverse is also true, so clients can match on either field and get the same answer. Each code also has one fixed HTTP status. If ORDER_NOT_FOUND returns 404 in one place and 400 in another, clients cannot rely on the status, and you lose part of the reason for having a catalog.
Treat codes as public API. You can add a new code at any time. You can deprecate an old one by marking it, documenting its replacement and continuing to emit it until clients migrate. You must never rename a code or reuse it for a different meaning without notice. Clients have conditional logic tied to these strings, and a silent change breaks that logic without producing an error.
Granularity takes judgement. A very fine-grained catalog fills up with near-duplicates that nobody can tell apart. A very coarse one sends clients back to parsing detail strings. Use this rule: add a code only when a client would act differently because of it.
| Code | Type URI | Status | Client action |
|---|---|---|---|
AUTH_TOKEN_EXPIRED |
/errors/auth/token-expired |
401 | Refresh token, retry |
ORDER_NOT_FOUND |
/errors/order/not-found |
404 | Show missing-resource state |
PAYMENT_CARD_DECLINED |
/errors/payment/card-declined |
402 | Prompt for another card |
RATE_LIMIT_EXCEEDED |
/errors/rate-limit/exceeded |
429 | Back off, retry later |
How do you share error codes across Node.js services?
A catalog only helps if services can't drift from it, so publish it as code rather than a wiki page. The usual shape is a small internal package, or a module generated from a schema file, that exports two things. The first is a catalog object mapping each code to its type URI, HTTP status and default title. The second is a base error class, such as AppError, that takes a catalog key plus optional detail and extension fields. Services then throw new AppError('PAYMENT_CARD_DECLINED', { detail }), or call a factory like errors.cardDeclined(...), and never assemble a response body themselves. In TypeScript, typing the key as a union of catalog keys means a misspelled code fails at compile time instead of in production.
Sharing a package introduces coupling. Services upgrade on different schedules, so a newer service can emit PAYMENT_CARD_EXPIRED before an older service or a mobile client has a version that knows the code exists. Treat this version skew as normal. Clients should branch on known codes, and when a code is unknown they should fall back to handling by status class: a 4xx gets generic validation messaging, a 5xx gets retry-or-apologize. Adding a code should never break a consumer. Only removing a code or changing its meaning counts as a breaking change.
The time savings come from three places:
- One place to change. Renaming a title or adjusting a status is a single package release, not a search across repositories.
- Predictable branching for clients. Consumers switch on a stable
codefield instead of parsing message strings. - Fewer review debates. Code review no longer covers error shapes, because only one way to raise an error exists.
// errors/catalog.ts: single source of truth, published as an internal package
export const catalog = {
PAYMENT_CARD_DECLINED: { type: '/errors/payment-card-declined', status: 402, title: 'Card declined' },
PAYMENT_CARD_EXPIRED: { type: '/errors/payment-card-expired', status: 402, title: 'Card expired' },
ORDER_NOT_FOUND: { type: '/errors/order-not-found', status: 404, title: 'Order not found' },
} as const;
// Union of catalog keys, so a misspelled code fails at compile time
export type ErrorCode = keyof typeof catalog;
export class AppError extends Error {
readonly status: number;
constructor(readonly code: ErrorCode, readonly opts: { detail?: string; extensions?: Record<string, unknown> } = {}) {
super(opts.detail ?? catalog[code].title);
this.name = 'AppError';
this.status = catalog[code].status;
}
// Shared error middleware calls this. Services never build bodies by hand.
toProblem() {
const { type, title, status } = catalog[this.code];
return { ...this.opts.extensions, type, title, status, code: this.code, detail: this.opts.detail };
}
}
// In a service: throw new AppError('PAYMENT_CARD_DECLINED', { detail: 'Issuer declined the charge.' });
// Client side: branch on known codes, and fall back on status class for unknown ones
export function messageFor(body: { code?: string; status: number }): string {
switch (body.code) {
case 'PAYMENT_CARD_DECLINED': return 'Your card was declined. Try another card.';
case 'ORDER_NOT_FOUND': return 'We could not find that order.';
default:
// Unknown code, such as one added by a newer service. This must not break the client.
return body.status >= 500
? 'Something went wrong on our side. Please retry.'
: 'Please check your request and try again.';
}
}
This example shows a shared TypeScript error catalog and AppError class that services throw instead of building response bodies, plus a client handler that branches on known codes and falls back to the HTTP status class when it sees a code it doesn't recognize.
Implementing a single Express error-handling boundary
Express recognizes an error handler by its arity: a function declared with four parameters, (err, req, res, next). Register it after every route and router so that it is the one place where errors become responses. Its first job is to check res.headersSent. If a response is already streaming, writing a new body fails, so delegate to next(err) and let Express close the connection.
Async errors need explicit handling. How a rejected promise reaches the handler differs between Express major versions, so check the behavior of the version you run. Code that calls next(err) in a catch, or a small wrapper that attaches .catch(next) to each async handler, works the same in every version.
Map known errors into your catalog before falling back:
- Malformed JSON from the body parser becomes a 400 with a parse-error
code. - Schema validation failures become a 422 or 400 with an
errorsarray that holds one entry per field, each with a pointer and a reason. - Unmatched routes go to a catch-all middleware, registered before the handler, that raises your not-found error.
- Auth failures and enumeration-sensitive paths, such as login or password reset, return deliberately vague responses. "Invalid credentials" should not reveal which part was wrong.
- Upstream timeouts become a 504 or 503.
Anything unrecognized becomes a generic 500 with a fixed detail. Never put the stack or the original message in it.
Keep the client view and the operator view separate. The response carries only the safe detail and the request ID. The structured log, keyed by the same ID, records the full error, stack and cause. Log 4xx responses at warn and 5xx at error, so alerts track server faults rather than client mistakes.
// Domain error carrying a catalog code and a client-safe detail.
class AppError extends Error {
constructor(status, code, detail, { errors, cause } = {}) {
super(detail, { cause });
Object.assign(this, { status, code, detail, errors });
}
}
// Forwards rejected promises to next(); behaves the same on any Express major.
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
// Catch-all for unmatched routes, registered after all routers.
app.use((req, res, next) =>
next(new AppError(404, 'not-found', 'Resource not found')));
// The single error boundary: four parameters, registered last.
app.use((err, req, res, next) => {
if (res.headersSent) return next(err); // Let Express close the connection.
let p;
if (err instanceof AppError) {
p = { status: err.status, code: err.code, detail: err.detail, errors: err.errors };
} else if (err.type === 'entity.parse.failed') { // body-parser JSON failure
p = { status: 400, code: 'malformed-json', detail: 'Request body is not valid JSON' };
} else {
// Unknown error: fixed detail, never err.message or the stack.
p = { status: 500, code: 'internal', detail: 'An unexpected error occurred' };
}
// Operator view: full error, stack and cause, keyed by the request ID.
// req.id is assumed to be set by earlier request-ID middleware.
const level = p.status >= 500 ? 'error' : 'warn';
logger[level]({ requestId: req.id, status: p.status, err, stack: err.stack, cause: err.cause }, err.message);
// Client view: safe fields and the request ID only.
res.status(p.status).type('application/problem+json').json({
type: 'about:blank', status: p.status,
code: p.code, detail: p.detail, errors: p.errors, requestId: req.id,
});
});
A last-registered Express error handler that checks headersSent, maps domain and JSON parse errors to Problem Details, hides unknown errors behind a generic 500, and logs full details at warn or error by request ID.
How should errors propagate between services and non-HTTP transports?
client ──► gateway ──────────► service A ──────────► service B
▲ │ translate │ wrap │ originates
│ │ (public catalog) │ (keeps B's code │ ORDER_STOCK_UNAVAILABLE
│ │ │ as `cause`) │
└── 409 ORDER_UNAVAILABLE ◄─────┴─────────────────────┘
request/trace ID forwarded unchanged on every hop
Each hop needs a deliberate choice about what to do with a downstream error code:
| Strategy | Benefit | Cost |
|---|---|---|
| Pass through | Full fidelity, no extra code | Leaks internal topology; external clients become coupled to service B's codes |
| Wrap | Caller owns its contract, original kept as cause for logs |
Nesting must be capped, or responses grow with each hop |
| Translate | Clean public contract at the edge | Loses detail; mapping tables drift as services add codes |
A common split is to wrap between internal services and translate once at the gateway. That keeps the drifting mapping in one place. The correlation ID must survive every hop unchanged, because it is the only thing that connects the translated public error to B's original log entry.
The Express error middleware only sees errors passed to next() or thrown in handlers it wraps. Errors from these sources never reach it:
- stream
errorevents - background jobs
- unhandled
EventEmittererrors - failures after headers are sent
Once headers are out, you cannot send a Problem Details body. You can only destroy the connection and log the failure with the request ID.
Message queues and gRPC have their own failure semantics: dead-letter reasons and gRPC status codes. Map both to the same catalog, carrying the code in message headers or gRPC metadata. If you skip this, the error contract is consistent over HTTP and breaks at those boundaries.
request ---------------------------------------------------------->
==== X-Request-ID forwarded unchanged on every hop ===============>
+--------+ +-------------+ +--------------+ +--------------------+
| client |<--| gateway |<--| service A |<--| service B |
| | | TRANSLATE | | WRAP | | ORIGINATES |
| | | to public | | B's code | | ORDER_STOCK_ |
| | | catalog | | kept as | | UNAVAILABLE |
| | | (one map) | | `cause` | | |
+--------+ +-------------+ +--------------+ +--------------------+
409 ORDER_UNAVAILABLE no pass-through: B's codes stay internal
+---------------------------------------------------------------------+
| inside each service |
| |
| handler throw / next(err) --> error middleware --> Problem Details |
| |
| NOT reached by middleware --> own handler, log with request ID |
| - stream 'error' events |
| - background jobs |
| - unhandled EventEmitter 'error' events |
| - failures after headers sent: destroy socket, no body |
+---------------------------------------------------------------------+
+----------------+ +--------------------+ +----------------+
| message queue |---->| shared error code |<----| gRPC |
| dead-letter | | catalog | | status code + |
| reason, headers| | (same as HTTP) | | metadata |
+----------------+ +--------------------+ +----------------+
Service B originates a code, service A wraps it as cause, and the gateway translates it once to the public catalog while the request ID passes unchanged through every hop; errors the central middleware never sees need their own handling, and queue and gRPC failures map to the same catalog.
How can a shared error contract save engineering time?
The savings come from removing work that otherwise repeats in every service and every client:
- Client teams write one error handler. Without a contract, a frontend or SDK needs per-service parsing for each error shape. With one, a single function that switches on
codeand falls back on status class covers every service, including codes added later. - Fewer breakages from message changes. Clients that branch on
codedon't break when someone rewords adetailstring or adds a translation, so those changes stop causing bug reports and hotfixes. - Faster debugging. Every error response carries a request ID that matches a structured log entry with the full stack and
cause. An engineer can go from a user's error report to the originating service's log without first working out which service and which format produced it. - Less time in code review. Services throw catalog errors through one boundary, so reviewers don't have to check status choices, body shapes or whether an internal message leaked into a response.
- Cheaper changes. Adjusting a title, a status or a
typeURI is a single package release instead of a coordinated edit across repositories. - Faster onboarding for new services. A new service gets the error format by installing the shared package and registering the boundary, instead of designing its own.
- Contract checks replace manual audits. Schema validation and CI rules catch ad-hoc error bodies automatically, so nobody has to audit services by hand to find drift.
These savings depend on the number of services and consumers. They are small for one service and one client, and they grow with each additional service and client team that would otherwise handle errors its own way. The illustrative estimate in the next section shows one way to weigh them against the setup cost.
How do you enforce the error contract and migrate existing services?
Enforcement has to be mechanical, or the contract erodes one hurried hotfix at a time. Define a single Problem schema as a shared OpenAPI component. Reference it from every 4xx and 5xx response, and generate the code enum from the catalog so the docs cannot drift from the package. Write contract tests that trigger each documented failure, validate the body against that schema and assert the code is listed for that endpoint. In CI, reject any res.status(...).json(...) outside the error boundary. A custom lint rule or a simple pattern check is enough, because ad-hoc bodies are almost always written that way.
Migration is the harder part. Clients that read body.message or body.error break when the shape changes.
| Strategy | How it works | Operational cost |
|---|---|---|
| Versioned endpoints | /v2 returns Problem Details |
Two route trees to maintain and monitor |
| Content negotiation | Problem Details only when Accept includes application/problem+json |
Low code cost, but clients can stay on the old format indefinitely |
| Dual fields | Old fields sit next to type, code and detail for a fixed window |
Larger payloads, plus tracking who still reads the old fields |
The upfront work is real: the catalog, the shared package, the docs and the CI checks. After that, someone has to review new codes. Illustrative estimate: assume 12 services, three weeks of setup and one hour per week of governance. If each client team avoids two hours a month of per-service special casing, the setup pays for itself within the first year.
Adopt this incrementally when several teams consume your APIs. Start with new endpoints, then move to dual fields. Defer it if you run one service with one client and both are owned by the same team.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to rest api error format, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.