NODEJS Contents

Standard Error Response Format in Express

A consistent error format turns failures into a stable API contract, improving client behavior, monitoring, and incident response.

On this page

Why Error Format Matters

In production, clients and monitoring depend on predictable errors. A stable error shape enables retries, user messaging, and alert routing based on error codes instead of fragile text matching.

Recommended Error Shape

Return a top-level error object with stable code, a safe message, and optionally details for validation problems. Include a requestId to support debugging.

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request",
    "requestId": "d7f2b5f1-..."
  }
}

Mapping Rules

  • Validation errors: 400 + field issues
  • Auth errors: 401/403 with no secret leakage
  • Not found: 404 with stable code
  • Unexpected errors: 500 with generic message

Production Rule

Do not expose stack traces. Log them internally with request context and return safe errors externally.