Skip to content
Back to skills

Fastapi Errors Logging

ASecurity

Central error-handling patterns and safe structured logging for FastAPI - DomainError taxonomy, per-technology errors.py with guard decorators, a single classifier shared by HTTP/WebSocket/jobs, safe RFC 9457 problem bodies, an optional security-signal integration, correlation ids and a unique error-code catalog. Use whenever the user asks about error handling, exceptions, error responses, logging, logs not clear, tracing a request across API and workers, correlation ids, redaction, or "why c...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 27, 2026
developmentrustgofastapigitapisecurity

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 27, 2026

npx -y skills add amralhorimy/fastapi-pro-skills --skill fastapi-errors-logging --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Fastapi Errors Logging?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Fastapi Errors Logging
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/amralhorimy-fastapi-errors-logging/badge)](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-errors-logging)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: fastapi-errors-logging
description: Central error-handling patterns and safe structured logging for FastAPI - DomainError taxonomy, per-technology errors.py with guard decorators, a single classifier shared by HTTP/WebSocket/jobs, safe RFC 9457 problem bodies, an optional security-signal integration, correlation ids and a unique error-code catalog. Use whenever the user asks about error handling, exceptions, error responses, logging, logs not clear, tracing a request across API and workers, correlation ids, redaction, or "why can't I follow what happened".
---

# Errors and Logging

Principle: **what helps us (traceback, internal cause) is dangerous to the client; what helps the client (polite
message, stable code) is not enough for us.** So every failure has two paths that meet at **one classifier** and are
tied together by one **correlation id**. Reference code: `references/core.py`.

```
library exception (pymongo, redis, minio, firebase)
   -> adapter guard translates to our taxonomy (DependencyUnavailable...)       platform/<tech>/errors.py
domain/application raise DomainError subclasses                                   shared/errors.py + module errors.py
any unexpected bug
                         \
                          platform/errors/classify.py : exc -> ErrorInfo(code, status, severity, public message, expected)
                              |-- Path 1 (us)      reporting.py : safe structured classification; raw exception text/traceback is opt-in only after redaction review
                              |-- Path 2 (client)  problem.py / http.py / ws.py : safe body + X-Request-ID
                              '--> Path 3 (optional integration) selected codes can become security events (see fastapi-security)
```

## Taxonomy (`shared/errors.py`, stdlib only)
`DomainError(code, default_detail, severity, public_extra_keys, log_extra_keys)` with categories. `default_detail` is reviewed,
static client-safe text; a per-instance `detail` is diagnostic-only and must not be returned by default.
`NotFound(404) Conflict(409) Forbidden(403, WARNING) Unauthorized(401) InvalidInput(422) DependencyUnavailable(503, ERROR)
RateLimited(429, WARNING)`. Business code never knows HTTP status codes - `classify` maps category -> status.

- `extra` kwargs are split: only keys in `public_extra_keys` may reach the client; project logging may use `log_extra_keys`
  only after applying its data-minimization/redaction policy. The bundled reference does not log those values. Everything else
  is dropped. Public extras are extension fields only and cannot replace RFC 9457 fields; validate their values and
  `retry_after` as bounded positive integer seconds (the reference accepts 1–86400).

## Rules
1. **Every technology owns an `errors.py`** with its error classes and a guard (`mongo_guard`, `redis_guard`,
   `storage_guard`, `firebase_guard`). Put the guard on every adapter class: callers never see a driver exception.
2. **Application catches only specific types** (`except DependencyUnavailable`) - a dead cache degrades gracefully; a bug in
   cache code fails loudly. Never `except Exception` outside process boundaries.
3. **Log once, at the boundary** (HTTP handler, WS handler, job runner). No `logger.exception` in inner layers.
   `report()` marks the exception so it can never be logged twice.
4. **The client message is never built from exception text.** Unexpected errors get a generic message + validated `request_id`;
   domain errors use reviewed static `default_detail`, not a caller-supplied `detail`.
   Validation errors return sanitized locations and a generic message; do not pass through custom validator text or submitted
   values, because either may contain credentials or personal data.
5. **Unique code per error**, enforced by a test that walks all `DomainError` subclasses; catalog in `docs/errors.md`.
6. **Same behaviour in every channel**: HTTP, WebSocket frames and background jobs all call `classify`.
7. Level by meaning: domain 4xx -> INFO (Forbidden -> WARNING); dependency down -> ERROR; unexpected -> ERROR,
   `error_expected=false`. The bundled reference logs only safe error codes/types and bounded route metadata; it does not log
   raw messages or tracebacks. Add deeper diagnostics only through an access-controlled sink with tested redaction, and state
   what remains unavailable rather than claiming that exception details are safely redacted by default.
8. Response body = **RFC 9457** `application/problem+json`: `type, title, status, detail, instance, code, request_id,
   timestamp`. Keep legacy fields only while old clients need them, with a note on when to delete them.
9. 503/429 may carry a bounded, validated `Retry-After`. Do not impose a universal `WWW-Authenticate` scheme: the
   authentication adapter must supply its own challenge when required. Validate framework status codes and response headers;
   reject header injection and response-framing headers before forwarding them.

## Correlation id and context
- Pure ASGI middleware (never `BaseHTTPMiddleware` - it breaks streaming/SSE and cancellation) generates an internal id by
  default. It accepts `X-Request-ID` only when the immediate peer is in the explicitly configured trusted-proxy CIDRs and
  the value is well-formed; configure exactly the proxy addresses that overwrite the client header. Verify that the deployed
  ASGI server/middleware exposes the raw socket peer in `scope.client` (some proxy middleware rewrites it); otherwise leave
  the allow-list empty and generate a new internal id. Otherwise ignore it.
  `traceparent` is separate trace context and must never be treated as a request id or identity.
- The id appears on request logs. If actor context is needed, prefer a pseudonymous identifier and a minimal role label; apply
  privacy/retention controls and never log raw credentials or unnecessary personal data. Use a mutable holder created by the
  middleware for request-level context: a `ContextVar.set` inside a dependency does not propagate back to middleware code.
- **Propagate across processes**: put the id in every job/event payload; the worker re-binds it before handling, so one id
  reconstructs `message.sent -> notification.created -> notification.delivered` across API and worker.

## Log format
- `text` for development, `json` for production (`LOG_FORMAT`). **One line per message** (escape newlines so a message cannot
  forge a log line). Fixed envelope on every line, from every process:
  `ts, level, channel, logger, message, service, env, version(git sha), host, pid, request_id, actor_pseudonym, actor_role`
  + `http_*` (method, route template, status, duration_ms, slow), `client_*`, `error_*`, `sec_*`, `ctx_*`.
- **Channels** (`access / audit / security / app`) are derived from the logger name, not claimed by the caller; each channel has
  one legitimate writer, enforced by a test.
- Extra fields accepted **only with known prefixes** so nobody can overwrite the envelope.
- **Redaction in the formatter (last step)**: define and test redaction for JWT, Authorization headers, passwords, keys,
  credentials in URLs, PEM blocks, and sensitive fields; bound message length and escape control characters. Do not claim a
  regex is complete protection. The bundled reference avoids raw exception text/tracebacks instead of implementing a redactor;
  any richer formatter is project code and needs its own tests, access policy, and retention limits.
- Business flow events are dotted verbs (`post.liked`, `job.retry_scheduled`); facts as fields, not prose.

## Checklist
- [ ] Forced domain error, dependency outage (only on an isolated test stack) and a raised `RuntimeError` each give the right
      status/body and ONE safe log line with the same request id
- [ ] No driver exception type appears outside `platform/` or adapters; no bare `except`
- [ ] Error-code uniqueness test + `docs/errors.md` up to date
- [ ] Worker log lines carry the originating request's correlation id
- [ ] Secrets/tokens never appear in logs (redaction test with fixtures); raw exception text and traceback are disabled unless
      a separately tested, access-controlled diagnostic path is configured

## Reference boundary: security signals
`references/core.py` centralizes error classification/reporting, but by itself it does **not** implement
`ERROR_CODE_EVENTS`, write a dedicated security channel, increment security metrics, alert, or append audit entries. Wire a
single code-to-event mapper and the application's security logger/metrics/alert sink at the error boundary; test the mapping
and avoid emitting the same event from individual modules. A normal error log is not a security-event pipeline.

Files in this skill

  • SKILL.md8.5 KB
  • references/core.py20 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.