装饰器版本自定义异常

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"}

FastAPI中全局异常处理的更多相关文章

  1. ASP.NET MVC中全局异常处理

    以前不知道从哪里找到的处理全局异常的,觉得蛮好用就记下来了. 1, 建立MyExecptionAttribute.cs类,写入如下代码: using System; using System.Coll ...

  2. ASP.NET Core 中间件自定义全局异常处理

    目录 背景 ASP.NET Core过滤器(Filter) ASP.NET Core 中间件(Middleware) 自定义全局异常处理 .Net Core中使用ExceptionFilter .Ne ...

  3. 在.NET Core程序中设置全局异常处理

    以前我们想设置全局异常处理只需要这样的代码: AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledExc ...

  4. Global Error Handling in ASP.NET Web API 2(webapi2 中的全局异常处理)

    目前,在Web API中没有简单的方法来记录或处理全局异常(webapi1中).一些未处理的异常可以通过exception filters进行处理,但是有许多情况exception filters无法 ...

  5. Springboot集成Common模块中的的全局异常处理遇见的问题

    由于项目公共代码需要提取一个common模块,例如对于项目的文件上传,异常处理等,本次集成common代码时候maven引入common的全局异常处理代码之后发现不生效,由于common包路径与自己的 ...

  6. NET MVC全局异常处理(一) 【转载】网站遭遇DDoS攻击怎么办 使用 HttpRequester 更方便的发起 HTTP 请求 C#文件流。 Url的Base64编码以及解码 C#计算字符串长度,汉字算两个字符 2019周笔记(2.18-2.23) Mysql语句中当前时间不能直接使用C#中的Date.Now传输 Mysql中Count函数的正确使用

    NET MVC全局异常处理(一)   目录 .NET MVC全局异常处理 IIS配置 静态错误页配置 .NET错误页配置 程序设置 全局异常配置 .NET MVC全局异常处理 一直知道有.NET有相关 ...

  7. WEB 项目中的全局异常处理

    在web 项目中,遇到异常一般有两种处理方式:try.....catch....:throw 通常情况下我们用try.....catch.... 对异常进行捕捉处理,可是在实际项目中随时的进行异常捕捉 ...

  8. Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。

    通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...

  9. SpringBoot中的全局异常处理

    SpringBoot中的全局异常处理 本篇要点 介绍SpringBoot默认的异常处理机制. 如何定义错误页面. 如何自定义异常数据. 如何自定义视图解析. 介绍@ControllerAdvice注解 ...

  10. springboot中 简单的SpringMvc全局异常处理

    1.全局异常处理类:GlobalExceptionHandler.java package com.lf.exception; import java.util.HashMap; import jav ...

随机推荐

  1. [转帖]SpringBoot配置SSL 坑点总结【密码验证失败、连接不安全】

    文章目录 前言 1.证书绑定问题 2.证书和密码不匹配 3.yaml配置文件问题 3.1 解密类型和证书类型是相关的 3.2 配置文件参数混淆 后记 前言 在SpringBoot服务中配置ssl,无非 ...

  2. CentOS8 设置开机自动登录账户的方法

    CentOS8 设置开机自动登录账户的方法 修改/etc/gdm/custom.conf文件, 并且添加内容即可. vim /etc/gdm/custom.conf # 在配置节下添加如下内容. [d ...

  3. UData查询引擎优化-如何让一条SQL性能提升数倍

    1 UData-解决数据使用的最后一公里 1.1 背景 在大数据的范畴,我们经历了数据产业化的历程,从各个生产系统将数据收集起来,经过实时和离线的数据处理最终汇集在一起,成为我们的主题域数据,下一步挖 ...

  4. 【验证码逆向专栏】数美验证码全家桶逆向分析以及 AST 获取动态参数

    声明 本文章中所有内容仅供学习交流使用,不用于其他任何目的,不提供完整代码,抓包内容.敏感网址.数据接口等均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关! 本文章未经许 ...

  5. 4.5 MinHook 挂钩技术

    MinHook是一个轻量级的Hooking库,可以在运行时劫持函数调用.它支持钩子API函数和普通函数,并且可以运行在32位和64位Windows操作系统上.其特点包括易于使用.高性能和低内存占用.M ...

  6. 有用的sql笔记(工作总结)

    1.查询当前月(数字为0表示当前月份,1表示上个月,-1表示下个月,以此类推) SELECT DATE_FORMAT((CURDATE() - INTERVAL [数字] MONTH), '%Y-%m ...

  7. MD5算法:高效安全的数据完整性保障

    摘要:在数字世界中,确保数据完整性和安全性至关重要.消息摘要算法就是一种用于实现这一目标的常用技术.其中,Message Digest Algorithm 5(MD5)算法因其高效性和安全性而受到广泛 ...

  8. 学生成绩管理系统|Python小应用练习

    题目要求 实现学生成绩管理系统 输入学生成绩信息序列,获得成绩从高到低.从低到高.按某一门成绩的排列,相同成绩都按先录入排列在前的规则处理. 数据如下:(数据规则:学生姓名 高数成绩 英语成绩 大物成 ...

  9. CF1764H Doremy's Paint 2 题解

    题目链接:CF 或者 洛谷 高分题,感觉挺有意思的题,值得一提的是这个题的 \(1\) 和 \(3\) 版本却是两个基础题. 一开始以为跟这道差不多:P8512 [Ynoi Easy Round 20 ...

  10. 2022 JuiceFS 社区用户调研结果出炉

    为了使 JuiceFS 的发展更贴合用户的真实需求,我们在三周前向社区发出了一份调研问卷.此次调研面向已经将 JuiceFS 应用于生产环境的用户,了解其在应用 JuiceFS 前和使用中的体验与评价 ...