0
0
FastAPIframework~10 mins

Custom exception handlers in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AResponse
BHTTPException
CRequest
DFastAPI
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of FastAPI
Trying to instantiate HTTPException as the app
2fill in blank
medium

Complete the code to define a custom exception handler for HTTPException.

FastAPI
@app.exception_handler([1])
async def http_exception_handler(request, exc):
    return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
Drag options to blanks, or click blank then click option'
AException
BHTTPException
CResponse
DRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of HTTPException
Using the base Exception class which is too broad
3fill in blank
hard

Fix the error in the custom exception handler to return a JSON response.

FastAPI
from fastapi.responses import [1]

@app.exception_handler(ValueError)
async def value_error_handler(request, exc):
    return [1](status_code=400, content={"error": str(exc)})
Drag options to blanks, or click blank then click option'
APlainTextResponse
BHTMLResponse
CJSONResponse
DRedirectResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using PlainTextResponse or HTMLResponse which do not send JSON
Forgetting to import JSONResponse
4fill in blank
hard

Fill both blanks to create a custom exception and handler that returns a JSON error message.

FastAPI
class CustomError(Exception):
    def __init__(self, message):
        self.message = message

@app.exception_handler([1])
async def custom_error_handler(request, exc):
    return JSONResponse(status_code=[2], content={"error": exc.message})
Drag options to blanks, or click blank then click option'
ACustomError
B400
CHTTPException
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using HTTPException instead of CustomError in the handler decorator
Using wrong status code like 500
5fill in blank
hard

Fill all three blanks to raise a custom exception and handle it with a JSON response.

FastAPI
class MyException(Exception):
    def __init__(self, detail):
        self.detail = detail

@app.get("/error")
async def error_route():
    raise [1]("Something went wrong")

@app.exception_handler([2])
async def my_exception_handler(request, exc):
    return JSONResponse(status_code=[3], content={"error": exc.detail})
Drag options to blanks, or click blank then click option'
AMyException
BCustomError
C400
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Raising a different exception than handled
Using status code 500 instead of 400