DEV Community

Cover image for Debug HTTP 422 API Validation Errors Safely
Raylabs
Raylabs

Posted on Originally published at raylabs.app

Debug HTTP 422 API Validation Errors Safely

When an API returns an HTTP 422 response, client integrations often discard field-level details or dump entire response bodies into logs.

Quick solution:

async function readAndFormat422(response: Response): Promise<string> {
  const raw = await response.text();
  try {
    const body = JSON.parse(raw);
    const errors = body.errors;
    if (errors && typeof errors === "object") {
      return Object.entries(errors)
        .slice(0, 10)
        .map(([field, val]) => field + ": " + String(val))
        .join("; ");
    }
    return body.message || "Unprocessable content";
  } catch {
    return raw.slice(0, 200);
  }
}
Enter fullscreen mode Exit fullscreen mode

HTTP 422 is one of those status codes that is specific enough to sound useful and vague enough to waste an hour. The server understood the request content type and syntax, but could not process the instructions in the payload.

What HTTP 422 actually tells you

RFC 9110 defines 422 Unprocessable Content as a case where the server understands the content type and the syntax is correct, but cannot process the contained instructions. MDN’s 422 reference summarizes the status as well. Because providers return inconsistent error-body schemas, your client must handle varied shapes safely without assuming a universal structure.

The anti-patterns of error handling

Catching non-2xx responses by keeping only the status code strips out all valuable context, turning detailed validation failures into generic messages. Conversely, logging the raw response text directly often leaks user input, tokens, or unexpected internal details into your observability stack.

Redacting and bounding output

Always bound character lengths and field counts to prevent memory bloat or log floods, and sanitize sensitive patterns like bearer tokens before persistence. For related architectural workflows, consult Designing a Reliable Serverless AI Publishing Workflow and Building a Reliable Batch Publishing Workflow.

Verification checklist

  • Read error bodies exactly once as text before parsing.
  • Enforce structural limits on extracted error fields.
  • Sanitize output strings for authorization tokens.
  • Confirm 422 responses do not trigger infinite retry loops.

Top comments (0)