fastapi之自定义异常处理

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错误')

 

上一篇:swift_slowAlloc Crash 分析


下一篇:python异常处理之traceback.print_exc()跟traceback.format_exc()