$ recombobulate _
home / tips / use-claude-to-write-centralised-api-error-handling-middleware
0

Use Claude to Write Centralised API Error Handling Middleware

bagwaa @bagwaa · Mar 25, 2026 · Workflows
use-claude-to-write-centralised-api-error-handling-middleware

Inconsistent API error responses — different shapes for validation errors, auth failures, and server errors — make every frontend integration harder than it needs to be. Let Claude write centralised middleware to enforce a single contract.

Ask Claude: "Write Express middleware that catches all errors and returns consistent
JSON responses. Handle validation errors, auth failures, not-found errors, and
unexpected exceptions. Log unexpected errors with context, but never leak stack
traces to clients."

Claude generates middleware covering the full error surface — Zod/Joi validation failures, JWT auth errors, database constraint violations, and unhandled exceptions — all formatted to the same response shape:

// Every error returns this shape
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request data is invalid.",
    "details": [
      { "field": "email", "message": "Must be a valid email address" }
    ]
  }
}

For Laravel, ask Claude to update your app/Exceptions/Handler.php render method to normalise all exceptions — including third-party ones — into your API's contract with appropriate HTTP status codes:

// Claude maps exception types to consistent JSON shapes
public function render($request, Throwable $e): Response
{
    if ($request->expectsJson()) {
        return $this->renderApiException($e);
    }
    return parent::render($request, $e);
}

Claude will also write tests that assert each error type returns the correct HTTP status and shape — so the contract doesn't drift over time.

Consistent error responses make every API integration easier — and they're the mark of a backend built with care.

~/recombobulate $ tip --comments --count=0

Log in to leave a comment.

~/recombobulate $ tip --related --limit=3
0
Scan Pending Changes for Security Issues with /security-review

The /security-review command scans your uncommitted changes for injection vectors, auth gaps, hardcoded secrets, and other common vulnerabilities.

bagwaa @bagwaa · 1 hour ago
0
Run Setup Scripts on Every Session with the SessionStart Hook

The SessionStart hook fires when any session begins or resumes, making it ideal for loading environment variables and running one-time setup scripts.

bagwaa @bagwaa · 1 hour ago
0
Write Property-Based Tests with fast-check and Claude

Ask Claude to write property-based tests for your functions using fast-check — it identifies the mathematical invariants in your code and generates tests that cover inputs you'd never enumerate by hand.

bagwaa @bagwaa · 2 hours ago