Tutorial

How to Structure Error Responses for APIs

Return consistent, machine-readable error objects with a code, message, details, and request ID so clients can handle errors programmatically.

On this page

  1. Introduction
  2. The problem
  3. Design decisions
  4. Implementation
  5. Testing the boundary
  6. Common pitfalls
  7. Operational considerations
  8. Conclusion

Introduction

A 500 with a plain text message is useless to a client. It cannot branch on the error type, it cannot show a helpful message to the user, and it cannot correlate the error with a log entry. A structured error response fixes this: it has a stable code, a human-readable message, optional details about what failed, and a request ID for correlation. This guide designs an error response schema and a handler that maps every error to it.

The problem

When errors are ad hoc, every endpoint returns a different shape. Some return { error: “msg” }, some return { message: “msg” }, some return plain text. The client has to handle each endpoint differently, and the error messages are often generated by the framework with internal details. A consistent schema lets the client write one error handler and trust the structure.

Design decisions

The error response has four fields: code, a stable machine-readable string like VALIDATION_ERROR or NOT_FOUND; message, a human-readable string safe to show to users; details, an optional object with field-level errors or constraints; and requestId, a correlation ID for log lookup. The HTTP status matches the error category: 400 for validation, 404 for not found, 409 for conflict, 500 for internal. The handler maps known errors to the schema and wraps unknown errors in an INTERNAL_ERROR with the stack trace logged but not returned.

class ApiError extends Error {
  constructor(code, message, status, details) {
    super(message);
    this.code = code; this.status = status; this.details = details;
  }
}
const NotFound = (id) => new ApiError('NOT_FOUND', `Resource ${id} not found`, 404);
const ValidationError = (details) => new ApiError('VALIDATION_ERROR', 'Request validation failed', 400, details);

Implementation

The global error handler sits at the end of the middleware chain. It checks if the error is an ApiError and returns the structured response; otherwise it logs the full error with the request ID and returns a generic INTERNAL_ERROR. The request ID is generated at the start of the request and included in every error response and log entry, so a client can report the ID and the server can find the log entry. Validation errors include a details object with field names and constraint messages.

app.use((err, req, res, next) => {
  const requestId = req.id;
  if (err instanceof ApiError) {
    res.status(err.status).json({ code: err.code, message: err.message, details: err.details, requestId });
  } else {
    console.error('unhandled error', { requestId, err });
    res.status(500).json({ code: 'INTERNAL_ERROR', message: 'An unexpected error occurred', requestId });
  }
});

Testing the boundary

Test that a NotFound error returns 404 with code NOT_FOUND and the resource ID in the message. Test that a ValidationError returns 400 with field-level details. Test that an unhandled error returns 500 with code INTERNAL_ERROR and no stack trace. Test that every error response includes a requestId that matches the request log.

Common pitfalls

Avoid returning stack traces in production; they leak internal structure. Avoid using the HTTP status as the only error signal; it is too coarse for client logic. Avoid changing error codes between releases; clients depend on them. Avoid generic messages like “something went wrong” for known errors; the message should help the user or developer fix the problem. Avoid omitting the request ID; without it, errors cannot be correlated with logs.

Operational considerations

Use a stable, machine-readable error code as the primary identifier, not the HTTP status code and not a free-text message. The code is a string like VALIDATION_FAILED or QUOTA_EXCEEDED that the client switches on, and it never changes once a version ships, because clients write handlers keyed on the code. The HTTP status code is a coarse category and the message is for humans, so neither is stable enough to branch on. Document every code in a registry that lists the code, its HTTP status, its meaning, and the client action, so a client developer can find the handling guidance without reading the server source.

Include a request ID in every error response, generated on the server and also logged with the error. The request ID lets a client report an error and a server operator find the exact log entry, the trace span, and the upstream calls for that one request, without guessing at a timestamp. Put the request ID in a response header as well as the body, so a client that only logs headers still has it. The ID should be a UUID or a trace-native identifier, not a counter, because counters reset and collide across instances. Propagate the ID to downstream calls so the trace is complete.

For validation errors, include a details array with one entry per invalid field, each entry naming the field, the issue, and the rejected value. A single message like “invalid input” forces the client to parse text to find which field was wrong, and a client that shows a form cannot map the error back to the field. A details array lets the client highlight each field in place. For errors that are not field-specific, like a quota exceeded or a maintenance window, the details array is empty and the top-level code and message carry the full story. Keep the value field optional, because logging a rejected password or token value is a leak.

Log every error response server-side with the code, the request ID, the user, and the route, but not the full request body, which may contain secrets. Aggregate the error counts by code in a dashboard, so a code that spikes signals a regression or an attack. A code that never appears in production may be dead, or it may cover a path that is not exercised in tests; either way it is worth investigating. When a code is retired, keep it in the registry marked deprecated, because a client that still handles it should not get an unhandled-code error just because the server stopped documenting it.

Conclusion

Structured error responses make APIs debuggable and programmable. Define a schema with code, message, details, and requestId. Map every error to it, use the HTTP status for the category and the code for the specific reason, and include a request ID for correlation. Test every error path. The result is an API where clients can handle errors confidently and operators can trace them quickly.

Sources: JSON:API errors, RFC 9457 Problem Details.

FAQ

Should I use HTTP status codes or custom error codes?
Use both. The HTTP status gives the category; the custom code gives the specific reason, so clients can branch on the code without parsing the message.
Should error messages be localized?
Return a stable code and a default English message; let clients localize based on the code if needed. Do not rely on the message for logic.
How much detail should I include?
Include enough for the client to fix the request: which field failed, what the constraint was. Do not include stack traces or internal paths.

Related Examples