Skip to content
GreenSnippets

Build RFC 9457 problem details error responses

Return consistent, machine-readable API errors using the application/problem+json format.

JavaScript
function problem(status, title, { type = "about:blank", detail, instance, ...extensions } = {}) {
  const body = { type, title, status, ...(detail && { detail }), ...(instance && { instance }), ...extensions };
  return new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/problem+json" },
  });
}

Example / expected output

Output
return problem(422, "Validation failed", {
  detail: "The email field is not valid.",
  errors: [{ field: "email", message: "Invalid email" }],
});

How it works

RFC 9457 (which replaces RFC 7807) standardizes error bodies with type, title, status, detail and instance, plus any extra members you need. Clients can then handle errors generically. Keep detail free of stack traces and internal information.