Implement a custom exception handler to catch ItemNotFoundError and return 404
Tests FastAPI exception handler registration beyond HTTPException. A strong answer covers creating a custom exception, using app.exception_handler, and returning a JSONResponse with status 404 and a structured body. Red flag: per-route try/except, plain dict.
WHAT THIS TESTS: This question evaluates whether you know how to extend FastAPI's error handling beyond the built-in HTTPException. Interviewers want to see that you understand the Starlette exception handler mechanism underneath FastAPI, that you know how to register a global handler for a custom exception class, and that you can produce a properly structured HTTP response rather than letting the framework default to a 500 Internal Server Error.
A GOOD ANSWER COVERS: First, define a custom exception class such as ItemNotFoundError that inherits from Exception and optionally carries metadata like an item identifier. Second, register the handler at the application level using the app.exception_handler decorator or the add_exception_handler method. Third, implement the handler function with the exact signature async def handler(request: Request, exc: ItemNotFoundError) because FastAPI or Starlette injects both the request and the exception instance. Fourth, instantiate a JSONResponse with status_code set to 404 and a content dictionary containing fields like detail and item_id so the client receives a structured JSON body. Fifth, mention that once registered, any route raising ItemNotFoundError will automatically trigger this handler without manual try/except blocks in the endpoint.
COMMON WRONG ANSWERS: A major red flag is suggesting a try/except inside every route function to catch the custom exception and manually build a response; this defeats the purpose of centralized error handling. Another mistake is returning a plain Python dictionary from the handler instead of a JSONResponse object, which may work incidentally but reveals shallow familiarity with the response layer. Candidates sometimes confuse HTTPException with custom exceptions and suggest simply raising HTTPException with a 404 status, which ignores the requirement to map a domain-specific error to an HTTP response. Forgetting the request parameter in the handler signature or attempting to register the handler on a router instead of the app without understanding propagation rules are also warning signs.
LIKELY FOLLOW-UPS: An interviewer might ask how you would handle dozens of custom exceptions without repeating boilerplate, which leads to creating a base domain exception class or a registry mapping exceptions to status codes. They could ask how to override the default request validation exception handler to return a custom error format. Another follow-up is logging the exception inside the handler before returning the response, or asking how to add custom headers to the error response. You might also be asked how this integrates with middleware and whether the exception handler runs before or after middleware exit.
ONE CONCRETE EXAMPLE: Imagine an application where a service layer raises ItemNotFoundError when a database query returns no rows. You define the exception with a constructor that stores item_id. Then you write an async function custom_handler that accepts request and exc, constructs a JSONResponse with status code 404 and content set to a dictionary containing detail and item_id, and returns it. You attach this handler to the FastAPI app using app.add_exception_handler(ItemNotFoundError, custom_handler). Now when a path operation calls a service that raises this error, FastAPI catches it and returns the structured 404 response automatically.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.