CodePark/ questions / Idempotency keys, webhooks & errors
START PRACTICINGPRACTICE
Backend question · HTTP & API design › Idempotency keys, webhooks & errors

How would you design a consistent error response format for an API? What does RFC 9457 suggest?

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.shop.com/problems/validation",
  "title": "Request validation failed",
  "status": 422,
  "detail": "2 fields are invalid",
  "instance": "/orders",
  "errors": [{ "field": "quantity", "message": "must be at least 1" }]
}

Give every error the correct HTTP status and the same body shape. Then clients can handle all errors with one piece of code.

RFC 9457, "Problem Details for HTTP APIs", defines this shape. It replaces the older RFC 7807. Its media type is application/problem+json.

Its members are:

  • type: a URI that identifies the kind of problem. It can point to documentation.
  • title: a short, human-readable summary of that kind of problem.
  • status: the HTTP status code.
  • detail: an explanation of this specific occurrence.
  • instance: a value that identifies this specific occurrence.

You can add your own extension members. For example, add an errors array that lists which form fields failed validation.

In NestJS, a global exception filter is a good place to turn every exception into this shape. Don't leak stack traces or SQL errors, because they show attackers how your system works. Include a request ID or trace ID, so support can find the matching logs.

  • Every error uses the correct status code and the same body shape.
  • RFC 9457 defines problem details with the application/problem+json media type.
  • Its members are type, title, status, detail and instance, and you can add extension members.
  • A central exception filter builds the error body and never leaks internal details.