自定义异常
# 继承HTTPException
class TokenError(HTTPException):
pass
class UnicornException(Exception):
def __init__(self, name: str):
print("自定义异常类")
self.name = name
异常处理
from fastapi import FastAPI, HTTPException
from starlette.responses import JSONResponse
from uvicorn import run
from fastapi_04 import R
"""
中间件 & 依赖
"""
class TokenError(HTTPException):
pass
from fastapi import Request
# TokenError发生时,的处理
async def token_error(request: Request, exc: HTTPException):
return JSONResponse(R.fail("token认证失败").dict())
# https://www.starlette.io/exceptions/
exception_handlers = {
# 异常类:发生异常对应的处理方法
TokenError: token_error
}
app = FastAPI(title="异常处理", exception_handlers=exception_handlers)
class UnicornException(Exception):
def __init__(self, name: str):
print("自定义异常类")
self.name = name
from fastapi import Request
# 发生UnicornException 异常时 触发函数
@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("/fail")
async def fail():
raise UnicornException(name="demo")
return "fail"
@app.get("/ok")
async def ok():
raise TokenError(status_code=401)
if __name__ == "__main__":
# 启用web服务, reload -> 当改变代码时自动重启 # fastapi_02:app
run("__main__:app", reload=True)