FastAPI学习-24.自定义异常处理器 exception_handler

前言

添加自定义处理器,要使用 Starlette 的异常工具

安装自定义异常处理器

假设要触发的自定义异常叫作 UnicornException
且需要 FastAPI 实现全局处理该异常。
此时,可以用 @app.exception_handler() 添加自定义异常控制器:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

# 作者-上海悠悠 微信/QQ交流:283340479
# blog地址 https://www.cnblogs.com/yoyoketang/

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 也是如此。

posted @   上海-悠悠  阅读(243)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-09-29 python笔记65 - Python3 subprocess执行cmd命令行获取返回结果
点击右上角即可分享
微信分享提示