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.
Log in to leave a comment.
The /security-review command scans your uncommitted changes for injection vectors, auth gaps, hardcoded secrets, and other common vulnerabilities.
The SessionStart hook fires when any session begins or resumes, making it ideal for loading environment variables and running one-time setup scripts.
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.