fastapi之自定义异常处理


默认HttpExceptionError

# 默认HttpException 错误异常
@app04.get('/http_exception')
async def http_exception(city: str):
    if city != 'BeiJing':
        raise HTTPException(status_code=404, detail='city not found', headers={'x_token': 'xxx'})
    return {'message': 'no city'}

 

run.py 主程序中自定义异常

from starlette.exceptions import HTTPException as StarletteException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse


""" 改写默认的HttpException """


@app.exception_handler(StarletteException)  # 自定义HttpRequest 请求异常
async def http_exception_handle(request, exc):
    """

    :param request: 请求必不可少
    :param exc: 错误栈处理
    :return:
    """
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
"""自定义RequestValidationError 重写请求验证异常"""


@app.exception_handler(RequestValidationError)
async def request_validatoion_error(request, exc):
    """
      重写 request错误
    :param request: 必填项
    :param exc: 错误信息栈
    :return:
    """
    return PlainTextResponse(str(exc), status_code=exc.status_code)

chapter04程序抛出异常

""" 改写异常处理,每次使用自定义的异常处理"""


@app04.get(
    '/http_error/{city_id}',
    summary= '测试HttpError',
    description='接口测试: 测试自定义HttpError',
    tags=['HttpExceptionError'],
    status_code=666
)
async def overwhite_http_error(city_id: int):

    if city_id != 1:
        return city_id
    else:
        raise HTTPException(status_code=418, detail='city_id错误')

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM