FastAPI通用异常捕获及自定义异常消息实现问题
FastAPI异常处理问题解决方案
问题1:通用异常块捕获了所有异常(包括自定义HTTPException)
原因
当前代码中except Exception as e会捕获所有异常类型,包括你在try块中主动抛出的HTTPException,导致所有异常都进入通用处理逻辑。
解决方案
调整except块的顺序,先专门捕获HTTPException并重新抛出,再处理其他通用异常:
@app.get("/school/studentclass") async def get_student_class(id: int, stream: str, rank: int = 1): try: student = Student(id=id, stream=stream, rank=rank) # 修复:使用传入的rank参数而非固定值1 if student.id != 0: # 修复:逻辑判断用and,避免空字符串绕过校验 if student.stream is not None and student.stream.strip() != '': if student.rank != 0: studentClass = StudentClass() # 处理逻辑... return JSONResponse(content=studentClass.dict()) # 假设StudentClass是Pydantic模型,需转字典返回 else: raise HTTPException( status_code=422, detail="Student Rank is not right", headers={"X-Error": "Student Rank is not right"} ) else: raise HTTPException( status_code=422, detail="Student Stream is not right", headers={"X-Error": "Student Stream is not right"} ) else: raise HTTPException( status_code=422, detail="Student Id is not right", headers={"X-Error": "Student Id is not right"} ) except HTTPException: # 捕获HTTPException后直接重新抛出,交给FastAPI默认/自定义处理器处理 raise except Exception as e: # 仅处理非HTTPException的通用异常,返回指定格式 raise HTTPException(status_code=418, detail={"details": str(e)})
额外修复了代码中的两个逻辑问题:
student实例化时误用固定值1作为rank参数,改为使用传入的rank- 字符串非空判断用
or会导致空字符串绕过校验,改为and并添加strip()处理首尾空格
问题2:自定义CustomException无法生效
原因
你之前的写法是将CustomException作为HTTPException的detail参数传入,而非直接抛出CustomException,因此无法被识别为自定义异常类型。
解决方案
- 完善自定义异常类(可选,增加状态码属性增强灵活性):
class CustomException(Exception): def __init__(self, name: str, status_code: int = 422): self.name = name self.status_code = status_code
- 修改路由中抛出异常的逻辑,直接抛出
CustomException:
# 替换原来的raise HTTPException代码 raise CustomException(name="Invalid Student Rank")
- 为
CustomException添加专属异常处理器:
from fastapi import Request from fastapi.responses import JSONResponse @app.exception_handler(CustomException) async def custom_exception_handler(request: Request, exc: CustomException): return JSONResponse( status_code=exc.status_code, content={"details": exc.name} )
内容的提问来源于stack exchange,提问作者user14806829
相关产品推荐
相关产品推荐

