Bird
Raised Fist0
FastAPIframework~20 mins

Custom exception handlers in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
FastAPI Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a custom exception is raised in FastAPI?
Consider this FastAPI app with a custom exception and handler. What will the client receive when the endpoint is called?
FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class MyCustomError(Exception):
    def __init__(self, name: str):
        self.name = name

@app.exception_handler(MyCustomError)
async def custom_exception_handler(request: Request, exc: MyCustomError):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} caused an error."}
    )

@app.get("/error")
async def error_endpoint():
    raise MyCustomError("TestError")
A{"detail": "MyCustomError"} with status code 500
BA JSON response with message "Internal Server Error" and status code 500
CA plain text response with status code 200
D{"message": "Oops! TestError caused an error."} with status code 418
Attempts:
2 left
💡 Hint
Look at the exception handler's return value and status code.
📝 Syntax
intermediate
2:00remaining
Which option correctly registers a custom exception handler in FastAPI?
You want to handle a custom exception MyError globally in FastAPI. Which code snippet correctly registers the handler?
FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class MyError(Exception):
    pass

async def my_error_handler(request: Request, exc: MyError):
    return JSONResponse({"error": "MyError occurred"}, status_code=400)

# Which line correctly registers the handler?
Aapp.add_exception_handler(MyError, my_error_handler)
Bapp.register_exception_handler(MyError, my_error_handler)
Capp.exception_handler(MyError)(my_error_handler)
Dapp.handle_exception(MyError, my_error_handler)
Attempts:
2 left
💡 Hint
Check FastAPI's method to add exception handlers programmatically.
🔧 Debug
advanced
2:00remaining
Why does this custom exception handler not work as expected?
This FastAPI app defines a custom exception and handler but the handler is never called. Why?
FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class CustomError(Exception):
    pass

@app.exception_handler(Exception)
async def generic_handler(request: Request, exc: Exception):
    return JSONResponse({"error": "Generic error"}, status_code=500)

@app.get("/fail")
async def fail():
    raise CustomError()
ACustomError is not derived from Exception, so handler is not called.
BThe handler is missing the @app.exception_handler(CustomError) decorator.
CThe raise statement is incorrect syntax and never triggers the handler.
DThe generic handler for Exception overrides the CustomError handler, so CustomError handler is ignored.
Attempts:
2 left
💡 Hint
Check which exception the handler is registered for.
state_output
advanced
2:00remaining
What is the HTTP status code returned when a custom handler returns a JSONResponse with status 404?
Given this handler, what status code does the client receive when the exception is raised?
FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class NotFoundError(Exception):
    pass

@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError):
    return JSONResponse({"detail": "Item not found"}, status_code=404)

@app.get("/item")
async def get_item():
    raise NotFoundError()
A404
B500
C200
D400
Attempts:
2 left
💡 Hint
Look at the status_code argument in JSONResponse.
🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI custom exception handlers is true?
Select the correct statement about how FastAPI handles custom exceptions and their handlers.
ACustom exception handlers must return plain text responses, JSONResponse is not supported.
BFastAPI only allows one global exception handler for all exceptions and ignores specific ones.
CIf multiple handlers match an exception, FastAPI uses the most specific handler registered for the exception's class.
DException handlers must be synchronous functions; async handlers cause runtime errors.
Attempts:
2 left
💡 Hint
Think about inheritance and handler specificity.

Practice

(1/5)
1. What is the main purpose of a custom exception handler in FastAPI?
easy
A. To catch specific errors and return user-friendly responses
B. To speed up the server response time
C. To automatically fix bugs in the code
D. To log all incoming requests

Solution

  1. Step 1: Understand what exception handlers do

    They catch errors that happen during request processing.
  2. Step 2: Identify the benefit of custom handlers

    They allow sending clear, friendly messages instead of default error pages.
  3. Final Answer:

    To catch specific errors and return user-friendly responses -> Option A
  4. Quick Check:

    Custom handlers improve user experience = B [OK]
Hint: Custom handlers catch errors and explain them clearly [OK]
Common Mistakes:
  • Thinking they fix bugs automatically
  • Confusing with logging or performance tools
  • Assuming they speed up requests
2. Which of the following is the correct way to register a custom exception handler in FastAPI?
easy
A. app.add_exception_handler(MyException, handler_function)
B. app.register_handler(MyException, handler_function)
C. app.use_exception_handler(MyException, handler_function)
D. app.exception_handler(MyException, handler_function)

Solution

  1. Step 1: Recall FastAPI method for adding handlers

    FastAPI uses add_exception_handler to register handlers.
  2. Step 2: Check method names in options

    Only app.add_exception_handler(MyException, handler_function) uses the correct method name and parameters.
  3. Final Answer:

    app.add_exception_handler(MyException, handler_function) -> Option A
  4. Quick Check:

    Correct method is add_exception_handler = D [OK]
Hint: Use add_exception_handler to register custom handlers [OK]
Common Mistakes:
  • Using wrong method names like register_handler
  • Confusing decorator syntax with registration
  • Passing wrong parameters order
3. Given this code snippet, what will be the HTTP status code returned when MyException is raised?
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class MyException(Exception):
    pass

@app.exception_handler(MyException)
async def my_exception_handler(request: Request, exc: MyException):
    return JSONResponse(status_code=418, content={"message": "Custom error occurred"})

@app.get("/test")
async def test():
    raise MyException()
medium
A. 404
B. 418
C. 200
D. 500

Solution

  1. Step 1: Identify the status code in the handler

    The handler returns a JSONResponse with status_code=418.
  2. Step 2: Understand what happens when exception is raised

    Raising MyException triggers the handler, which sends the 418 status.
  3. Final Answer:

    418 -> Option B
  4. Quick Check:

    Handler sets status 418 = A [OK]
Hint: Check the status_code in JSONResponse inside handler [OK]
Common Mistakes:
  • Assuming default 500 error code
  • Confusing 404 with missing route
  • Ignoring custom status_code in handler
4. What is wrong with this FastAPI custom exception handler code?
from fastapi import FastAPI

app = FastAPI()

class CustomError(Exception):
    pass

@app.exception_handler(CustomError)
def handler(exc: CustomError):
    return {"error": "Something went wrong"}
medium
A. Return value must be a string, not a dict
B. Exception class must inherit from HTTPException
C. Handler function must be async and accept Request parameter
D. Decorator should be @app.add_exception_handler, not @app.exception_handler

Solution

  1. Step 1: Check handler function signature

    FastAPI expects async handler with parameters (Request, Exception).
  2. Step 2: Identify missing Request and async

    The handler lacks the Request parameter and is not async.
  3. Final Answer:

    Handler function must be async and accept Request parameter -> Option C
  4. Quick Check:

    Handler signature requires async and Request = C [OK]
Hint: Handler must be async and take Request as first argument [OK]
Common Mistakes:
  • Making handler synchronous
  • Omitting Request parameter
  • Thinking exception must inherit HTTPException
5. You want to create a custom exception handler in FastAPI that returns a JSON response with a dynamic message and a 400 status code whenever ValueError is raised. Which code snippet correctly implements this?
hard
A. from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(content={"error": str(exc)}, status=400)
B. from fastapi import FastAPI app = FastAPI() @app.exception_handler(ValueError) def value_error_handler(exc: ValueError): return {"error": str(exc), "status": 400}
C. from fastapi import FastAPI, Request app = FastAPI() @app.add_exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return {"error": str(exc), "status_code": 400}
D. from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": str(exc)})

Solution

  1. Step 1: Check correct decorator and function signature

    Use @app.exception_handler with async function taking (Request, Exception).
  2. Step 2: Verify JSONResponse usage and status code

    Return JSONResponse with status_code=400 and content with error message.
  3. Step 3: Identify correct option

    from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): return JSONResponse(status_code=400, content={"error": str(exc)}) matches all requirements exactly.
  4. Final Answer:

    A -> Option D
  5. Quick Check:

    Correct async handler with JSONResponse and status_code=400 = A [OK]
Hint: Use async handler with JSONResponse and status_code param [OK]
Common Mistakes:
  • Using synchronous handler
  • Missing Request parameter
  • Wrong decorator or status code parameter name
  • Returning dict instead of JSONResponse