Why Error Handling Matters
Without proper error handling, your API either crashes
or returns confusing responses. Frontend developers
need consistent, predictable error shapes to build against.
The Standard Error Shape
Every error in this API follows this exact structure:
{
"error": {
"message": "Reason for the error",
"status": 400
}
}
Consistent. Predictable. Professional.
3 Global Error Handlers
1. 404 Not Found
@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=404,
content={
"error": {
"message": "Resource not found",
"status": 404,
"path": str(request.url)
}
}
)
2. 400 Validation Error
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=400,
content={
"error": {
"message": "Invalid input data",
"status": 400,
"details": str(exc.errors())
}
}
)
3. 500 Internal Server Error
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={
"error": {
"message": "Internal server error",
"status": 500
}
}
)
Postman Tests
404 - Item not found
400 - Invalid input
404 - Invalid route with path
Lessons Learned
Global error handlers are not optional in production.
Every unhandled exception is a potential server crash
or a confusing response to the client. Define your
error shape once, apply it everywhere.
Day 12 done. 18 more to go.



Top comments (0)