---
name: handling-api-errors
description: Return HTTP API errors in one format, RFC 9457 Problem Details (application/problem+json), with accurate status codes, a trace ID, and no internal details, and test them. Use when writing or reviewing an HTTP API's error responses, error handlers, or their tests.
license: MIT
metadata:
author: famiglio
category: code
---
# Handling API Errors
Clients handle every error with the same code when every error has the same shape: [Problem Details](https://www.rfc-editor.org/rfc/rfc9457).
## Procedure
1. **Add one error handler** for the whole API, plus one for unknown routes, so the framework never returns its own error page.
2. **Return Problem Details:**
```http
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://example.com/problems/email-taken",
"title": "Email already in use",
"status": 409,
"detail": "Another account uses this email address.",
"traceId": "4bf92f3577b34da6"
}
```
- `type`: a stable URI for the kind of problem, or `about:blank` when the status says enough.
- `title`: a short summary that does not change between occurrences.
- `status`: the same code as the response.
- `detail`: a safe explanation of this occurrence.
3. **Choose the status code:**
| Code | Meaning |
<!-- ‹guest · 2026-12-05› -->
| ------------ | ---------------------------------------------------- |
| `400` | The request is malformed |
| `401` | The user is not signed in |
| `403` | The user is not allowed to do this |
| `404` | It does not exist, or you do not reveal that it does |
| `409` | It conflicts with the current state |
| `422` | The data is well formed but not valid |
| `429` | Too many requests; add a `Retry-After` header |
| `500`, `503` | Something failed on the server |
4. **Keep internals out.** For a `500`, return a generic `detail` and the trace ID. Log the error with its cause under the same ID (see the `writing-structured-logs` skill).
5. **Treat `type` URIs as part of the API.** Changing one is a breaking change.
## Verification
```bash
curl -sS -i http://localhost:3000/does-not-exist | grep -i '^content-type'
```
It prints `application/problem+json`. The integration tests check the status, the content type, and that `500` responses hold no stack trace or SQL.
این نسخه با نشانهگذاری اختصاصی حساب شما نمایش داده میشود. برای نصب سریع، به تب نصب و راهاندازی بروید.