首页 > 其他分享 >FastAPI中全局异常处理

FastAPI中全局异常处理

时间:2024-02-26 22:14:11浏览次数:25  
标签:status exception code FastAPI py user import 全局 异常

装饰器版本自定义异常

1.首先我们定义三个文件,分别为exception.py,main.py, user.py

2.自定义异常需要继承HTTPException,该异常可以从fastapi中直接导入
from fastapi import HTTPException

3.exception.py中定义我们业务模块的异常
from fastapi import HTTPException

class UserDoesNotExistsException(HTTPException):
  def __init__(self, detail: str, status_code: int):
    self.detail = detail
    self.status_code = status_code

4. user.py文件
router_user = APIRouter(prefix='/user', tags=['用户模块'])
@router_user.get('/{user_id}')
async def get_id_by_user(user_id: int):
    if user_id != 1:
        raise UserDoesNotExistsException(status_code=400, detail="id not exists")
    return {"user_id": user_id}

5.main.py文件
from fastapi import FastAPI
from exception import UserDoesNotExistsException
from user import router_user

app = FastAPI(debug=True)

# 这里就是添加使用我们自定义的错误处理
@app.exception_handler(UserDoesNotExistsException)
def user_exception_handler(req: Request, ex: UserDoesNotException):
    return JSONResponse(
        status_code=ex.status_code,
        content={"message": f'error: {ex.detail}'}
    )

app.include_router(router_user, prefix='/api/v1')

非装饰器版

第一种,通过在FastAPI()中指定exception_handlers

from fastapi import FastAPI
from fastapi.responses import JSONResponse

async def exception_not_found(request, exc):
    return JSONResponse({
        'code':exc.status_code,
        'error':'not found',
        status_code=exc.status_code
    })

exception_handlers = {
    # 键值对的形式,写具体的状态码或者具体的Exception子类都可以,后面完整例子中有
    404: exception_not_found,
}

app = FastAPI(exception_handlers=exception_handlers)

第二种,通过实例化的FastAPI对象的add_exception_handler方法

from fastapi import FastAPI
from fastapi.responses import JSONResponse

async def exception_not_found(request, exc):
    return JSONResponse({
        'code':exc.status_code,
        'error':'not found',
        status_code=exc.status_code
    })

app = FastAPI()
# 同理,可以写具体的状态码或者具体的Exception子类都可以
app.add_exception_handler(404, exception_not_found)

完整案例,项目中可以使用

1.定义四个文件,exception.py(全局处理), main.py(主程序文件), user/user.py(业务模块), user/exception.py(用户模块自己的错误处理)

2.exception.py文件
from fastapi import HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

# 全局异常       
async def global_exception_handler(request, exc):
    if exc.status_code == 500:
        err_msg = 'Server Internal Error'
    else:
        err_msg = exc.detail
    return JSONResponse({
        'code': exc.status_code,
        'err_msg': err_msg,
        'status': 'Failed'
    })

# 请求数据无效时的错误处理
""" 
example: http://127.0.0.1/user/{user_id}
success: http://127.0.0.1/user/1
failed: http://127.0.0.1/user/d
"""
async def validate_exception_handler(request, exc):
    err = exc.errors()[0]
    return JSONResponse({
        'code': 400,
        'err_msg': err['msg'],
        'status': 'Failed'
    })

golbal_exception_handlers = {
    HTTPException: global_exception_handler,
    RequestValidationError: validate_exception_handler
}

class BaseAPIException(HTTPException):
    status_code = 400
    detail = 'api error'
    def __init__(self, detail: str = None, status_code: int = None):
        self.detail = detail or self.detail
        self.status_code = status_code or self.status_code

3.定义user/exception.py
from exception import BaseAPIException

class UserDoesNotExistsException(BaseAPIException):
    status_code = 10000
    detail = 'user does not exists'

4.定义uers/user.py
from fastapi.routing import APIRouter

from .exception import UserDoesNotExistsException

router_user = APIRouter(prefix='/user', tags=['用户模块'])

@router_user.get("/{user_id}")
async def get_id_by_user(user_id: int):
    if user_id != 1:
        # 这里使用我们自定义的用户错误处理
        # 返回的统一响应格式{"code":10000,"err_msg":"user does not exists","status":"Failed"}
        raise UserDoesNotExistsException
    return {"user_id": user_id}

5.定义main.py
from fastapi import FastAPI
from exception import golbal_exception_handlers
from user.user import router_user

app = FastAPI(debug=True, exception_handlers=golbal_exception_handlers)

app.include_router(router_user, prefix='/api/v1')


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app='main:app', host='0.0.0.0', port=9002, reload=True)

6.响应
# example: http://127.0.0.1:9002/api/v1/user/2
{"code":10000,"err_msg":"user does not exists","status":"Failed"}
# example: http://127.0.0.1:9002/api/v1/user/d
{"code":400,"err_msg":"value is not a valid integer","status":"Failed"}

标签:status,exception,code,FastAPI,py,user,import,全局,异常
From: https://www.cnblogs.com/weiweivip666/p/18035656

相关文章

  • 第八章 异常控制流
    1.异常从给处理器加电开始,直到你断电为止程序计数器假设一个值的序列(\(a_k\)是\(I_k\)的地址)每次从\(a_k到a_{k+1}\)的过渡称为控制转移,这样的控制转移称为处理器的控制流系统必须对系统状态的变化(\(I_k和I_{k+1}\)的地址不相邻)做出反应,这些变化不是一些必要的机制(比如......
  • C#异常
    C#异常解决转载:https://www.cnblogs.com/txwtech/p/11836139.html右键项目--》属性--》生成--》高级--》语言版本选择你配置文件所对应的版本。或者:右键项目---》管理nuget程序包--》查找安装或者更新Microsoft.Net.Compilers......
  • WPF资源管理:窥探外部、窗体、全局和动态资源的秘密!
    概述:WPF中的资源管理机制包括外部资源、窗体资源、全局资源和动态资源。通过这些资源,开发者能够在应用程序中有效地组织、重用样式和模板,实现灵活的设计和运行时更改。这四种资源类型分别适用于不同的应用场景,为WPF应用程序提供了强大的扩展性和可维护性。在WPF(WindowsPresentat......
  • python GIL 全局锁
    GIL由来我们先思考一个问题:我们在前面介绍的 list 、 dict 等内建对象是 线程安全 的吗?在 Python 层面,list 、dict 等内建对象是线程安全的,这是最基本的常识。研究 list、dict 等内建对象源码时,我们并没有看到任何 互斥锁 的痕迹,这多少有点令人意外。以 li......
  • 20个改善编码的Python异常处理技巧,让你的代码更高效
    异常处理是写好代码的一个重要的方面,虽然许多开发人员都熟悉基本的try-except块,但是有很多更深入的知识可以使异常处理更高效、更可读和更python化。所以本文将介绍关于Python异常的20个可以显著改善编码的Python异常处理技巧,这些技巧可以让你熟练的掌握Python的异常处理。Python......
  • application全局配置
    #应用名称spring.application.name=hello_mybatis#下面这些内容是为了让MyBatis映射#指定Mybatis的Mapper文件mybatis.mapper-locations=classpath:mappers/*xml#指定Mybatis的实体目录mybatis.type-aliases-package=cn.edu.neu.hello_mybatis.entity#数据库驱动:spring.datasour......
  • 在K8S中,Pod能否实现对容器健康检查,如果服务有异常,该如何处理?
    在Kubernetes(K8S)中,Pod可以配置健康检查来监控容器的运行状态。Kubernetes提供了两种类型的健康检查:就绪探针(ReadinessProbe):就绪探针用于确定Pod中的容器是否准备好服务请求。如果探针失败,则Pod会被从对应的Service后端列表中移除,直到它通过就绪探针为止。这确保了只有健康的......
  • java异常
    java异常异常分类Throwable是所有异常子类的超类exception子类:编译器异常,进行编译,java程序出现问题error子类:错误,必须修改源代码产生过程JVM判断异常,并产生包含异常信息的对象,如果异常产生的方法没有try--catch方法,如果没有则把异常对象返回main方法main方法也判......
  • 异常 app key or app secret must be initialed
     物联网平台移动开发sdk。在android应用的问题。按照文档集成后,运行抛异常(仅调用SDKManager.init(this);)异常摘录片段如下:java.lang.RuntimeException:Unabletocreateapplicationcom.kong.home_iot_control.MainApplication:com.alibaba.cloudapi.sdk.exception.SdkExc......
  • shell脚本如何抛出异常
    shell如何抛出异常在Shell中,可以使用exit命令来退出脚本并返回指定的状态码。当需要抛出异常时,我们可以通过设置不同的状态码来表示不同类型的错误或异常情况。下面是一些常见的Shell异常处理方式及其对应的状态码:exit0:正常结束程序,没有发生任何异常。exit1:非正常结束程序,......