0
0
FastAPIframework~20 mins

Custom exception handlers in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.