Expected Errors, Bugs and Outages
Distinguish expected domain errors from server bugs and infrastructure outages, and structure machine-readable error responses with RFC 9457 Problem Details.
Contentsand lesson path
On this page
- Why it matters
- Classifying failures: expected errors, server bugs, and outages
- RFC 9457 problem details for HTTP APIs
- Information leakage and defence in depth
- Check your understanding
- Apply it
- Review prompt
Lessons of Error Handling & Structured Logging
- Expected Errors, Bugs and Outages Concept · 15 min
- One Place to Turn Exceptions into Responses Worked example · 25 min
- When the Database or an Upstream API Fails Concept · 20 min
- Lab: Structured Logs with Request IDs Lab · 25 min
- Check: Triage an Incident from the Logs Knowledge check · 6 questions
What you will learn
- Map domain and infrastructure exceptions to HTTP responses in one place, returning Problem Details bodies without leaking stack traces or internal data.
Prerequisites: FastAPI Fundamentals
01. Why it matters
Every software system eventually encounters failure. In a web API, how you report those failures decides whether a client can react to them or has to guess. A poorly designed API treats all errors identically: returning generic 500 Internal Server Error strings, burying error messages inside HTTP 200 responses, or dumping raw Python tracebacks directly into the response payload.
These habits cause three problems. Dumping internal stack traces leaks server file paths, library versions, and database table names to potential attackers. Returning vague error strings breaks automated client SDK parsers. And misclassifying client errors as internal server faults triggers spurious on-call alerts and, over time, alert fatigue. Handling failures well starts with sorting them into kinds and reporting each kind in one standard, machine-readable format.
With clear failure semantics, front-end and partner teams can write one error-handling path for your whole API instead of one per endpoint.
02. Classifying failures: expected errors, server bugs, and outages
To handle failures correctly, backend engineers classify every exception into one of three distinct categories:
- Expected domain errors (4xx client errors) occur when a client submits invalid input, references a nonexistent resource, or requests an action that violates business rules. Examples include entering an invalid email format (422), requesting a deleted book ID (404), or attempting to book an appointment slot that another user just reserved (409 Conflict). The client must be informed why the request failed so they can correct it.
- Internal server bugs (500 server errors) are unexpected software defects within your own application code: an unhandled
KeyError, an unanticipatedNoneTypeattribute access, or an unhandled division by zero. The client did nothing wrong, but your application crashed. In this scenario, the server must log the complete traceback internally and return a safe, generic 500 error body containing a unique request ID. - Infrastructure outages (502, 503 or 504 gateway and upstream errors) happen when an external dependency or infrastructure component fails. If your database connection pool is exhausted or a third-party payment gateway times out, the service is temporarily incapable of completing the request. Returning 503 Service Unavailable with a
Retry-Afterheader tells clients the outage is temporary.
Careful classification also protects downstream monitoring and alerting pipelines. If client validation errors are mistakenly emitted at ERROR log levels or returned with HTTP 500 status codes, site reliability dashboards light up with false alarms. Keeping client mistakes out of the server error rate means that when the on-call engineer is paged, the alert is far more likely to point at something the team must fix.
03. RFC 9457 problem details for HTTP APIs
Historically, every API team invented their own custom JSON error schema. One company returned {"error_message": "..."}, another used {"errors": [{"msg": "..."}]}, and a third used {"code": 1042}. The Internet Engineering Task Force (IETF) first standardised a common, machine-readable error format in RFC 7807 (2016). RFC 9457: Problem Details for HTTP APIs (2023) replaced it with minor updates, such as a registry of common problem types, so libraries that say "RFC 7807" produce the same format.
An RFC 9457 response carries the media type application/problem+json and defines five standard JSON fields:
type(URI reference): A URI that identifies the specific problem type (e.g.,https://api.example.com/errors/slot-already-reserved). When dereferenced, it should provide human-readable documentation for that error class.title(string): A short, human-readable summary of the problem type (e.g., "Slot Already Reserved"). It should not change from occurrence to occurrence.status(integer): The HTTP status code generated by the origin server (e.g., 409).detail(string): A human-readable explanation specific to this occurrence of the problem (e.g., "The appointment slot at 14:00 on 2026-10-28 was booked by another user").instance(URI reference): A URI reference identifying the specific occurrence of the problem, often pointing to the request URI or a unique error log tracking path.
A response may leave type out. The client must then treat it as about:blank, a type that means "no more than the status code says", and the title should be the standard phrase for that status, such as "Not Found" for 404. An SDK that switches on type therefore needs an about:blank branch that falls back to the status code.
{
"type": "https://api.example.com/errors/slot-already-reserved",
"title": "Slot Already Reserved",
"status": 409,
"detail": "The slot at 14:00 on 2026-10-28 was booked by another user.",
"instance": "/appointments/slots/9182",
"request_id": "req_01h7v8k4b39m"
}RFC 9457 explicitly allows adding custom extension members to the JSON document. In the example above, "request_id": "req_01h7v8k4b39m" is a custom extension field. When a user contacts support with an error report, quoting the request ID allows operations and on-call engineers to find the exact correlated server log entry within seconds.
04. Information leakage and defence in depth
Error handling is part of an API's security. The OWASP API Security Top 10 (2023 edition) names "error messages include stack traces, or expose other sensitive information" as one sign of API8:2023 Security Misconfiguration.
When an unhandled database exception occurs (such as a database query timeout or unique key collision), the exception message and its traceback can contain the SQL text, table and column names, the database user and file paths on the server. If these details leak into HTTP responses, malicious actors can map your database schema and craft targeted SQL injection attacks.
This is why the lesson speaks of defence in depth: do not rely on one safeguard. Even if an attacker finds an injection flaw, a generic error body denies them the schema details that make it easy to exploit, so the second layer still slows them down.
The rule that follows is strict separation between client responses and server logs:
- Clients receive: An RFC 9457 JSON body with a generic title ("Internal Server Error"), a fixed status code (500), and a correlation request ID.
- Internal logs receive: The exception type, message and stack trace, recorded under the same request ID in structured JSON. Do not log request bodies, headers or local variables wholesale: they routinely contain passwords, tokens, session cookies and personal data, and log storage is usually read by more people and kept longer than the database. Log selected, scrubbed fields instead, and check that your error-tracking tool does not capture local variables by default.
05. Check your understanding
06. Apply it
Inspect your existing API endpoints. Identify any places where unexpected database errors might leak internal column names or queries to users. Audit your status codes to confirm that validation errors return 422 or 400 rather than 500. In the next lesson, you will implement centralised FastAPI exception handlers that format every error into standard RFC 9457 Problem Details.
07. Review prompt
Define the differences between expected domain errors, server bugs, and infrastructure outages. Name the five standard fields of an RFC 9457 Problem Details document, and explain why leaking internal stack traces in HTTP responses violates the principle of defence in depth.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.