fastapi HTTP异常处理

HTTPException是FastAPI中用于处理HTTP错误的异常类。HTTPException 是一个非常有用的异常类,用于当HTTP请求处理过程中遇到错误时,能够优雅地返回HTTP错误响应给客户端。通过抛出 HTTPException,你可以控制返回给客户端的HTTP状态码和响应体,使得客户端能够根据这些信息作出相应的处理。

一、简单用法

from fastapi import APIRouter,HTTPException

@user.get('/book')
async def boot():

    raise HTTPException(status_code=500,detail='this is a test')
    
    
# 客户端调用输出:
# 状态码status_code:500
# body:{"detail":"this is a test"}

 

二、自定义异常

2.1、exception/excepts.py 自定义HTTP异常处理

from fastapi import HTTPException
from typing import Any

class BaseException(HTTPException):
    status_code = 500
    detail = '服务器异常'
    data = None
    def __init__(self,**kwargs:Any):
        super().__init__(self.status_code,self.detail)
        self.status_code = kwargs.get('status_code', self.status_code)
        self.detail = kwargs.get('detail',self.detail)
        self.data = kwargs.get('data', self.data)


class Failed(BaseException):
    status_code = 500
    detail = '服务器异常'
    data = None


class UnAuthentication(BaseException):
    status_code = 401
    detail = 'Authentication Failed'

 

2.2、exception/__init__.py 全局异常处理

from fastapi.responses import JSONResponse

async def exception_user(request, exc):
    return JSONResponse({
        'code':exc.status_code,
        'message':exc.detail,
        'data':exc.data
    },
        status_code=exc.status_code) # 状态码

 

2.3、main.py 使用 add_exception_handler 方法添加到app实例

from fastapi import FastAPI,Request,HTTPException
from exception import exception_user

app = FastAPI()
# 添加到app
app.add_exception_handler(HTTPException, exception_user)

 

2.4、raise 自定义HTTP异常

from fastapi import APIRouter,Depends
from exception.excepts import Failed
from plugin.pulgin_sqlalchamy import db
from sqlalchemy.orm import Session
from models.cms.user import User

user = APIRouter()

def get_db():
    try:
        yield db
    finally:
        db.close()

@user.post('/dev')
async def dev(data:dict,db: Session = Depends(get_db)):
    user = db.query(User).filter_by(username = data['username'],password = data['password']).first()
    if not user:
        raise Failed(detail= '用户不存在')
        
    return user
        
# 调用dev接口
# 状态码status_code: 500
# body:{"code":500,"message":"用户不存在","data":null}

 

posted @ 2024-09-11 12:02  三只松鼠  阅读(18)  评论(0编辑  收藏  举报