前言
添加自定义处理器,要使用 Starlette 的异常工具。
安装自定义异常处理器
假设要触发的自定义异常叫作 UnicornException
。
且需要 FastAPI 实现全局处理该异常。
此时,可以用 @app.exception_handler()
添加自定义异常控制器:
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yoyo":
raise UnicornException(name=name)
return {"unicorn_name": name}
请求 /unicorns/yoyo
时,路径操作会触发 UnicornException
。
但该异常将会被 unicorn_exception_handler
处理。
接收到的错误信息清晰明了,HTTP 状态码为 418
,JSON 内容如下:
{"message": "Oops! yoyo did something. There goes a rainbow..."}
from starlette.requests import Request
和 from starlette.responses import JSONResponse
也可以用于导入 Request
和 JSONResponse
。
FastAPI 提供了与 starlette.responses
相同的 fastapi.responses
作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,Request
也是如此。