广告
返回顶部
首页 > 资讯 > 后端开发 > Python >FastAPI--错误处理(5)
  • 377
分享到

FastAPI--错误处理(5)

错误FastAPI 2023-01-31 08:01:26 377人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

HttpException异常抛出再之前Bottle 中其实有一个就是HttpError异常类,在Fastapi也存在这么一个HTTPException。比如:import uvicorn from fastapi&nb

HttpException异常抛出

再之前Bottle 中其实有一个就是HttpError异常类,在Fastapi也存在这么一个HTTPException。比如:

import uvicorn
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

在上面的代码中,通过判断item_id是不是存在于items来主动的抛出了一个404的错误

 

 访问一个错误的url

http://127.0.0.1:8000/items/asda

1.png

 

 我们查看HTTPException和StarletteHTTPException的源码发现他们也是继承与Exception:

class HTTPException(StarletteHTTPException):
    def __init__(
        self, status_code: int, detail: Any = None, headers: dict = None
    ) -> None:
        super().__init__(status_code=status_code, detail=detail)
        self.headers = headers

所以我们对于异常通常可以直接的使用 raise来抛出异常。

 

HTTPException且返回新增自定义请求头

import uvicorn
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}

@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
    if item_id not in items:
        raise HTTPException(
            status_code=404,
            detail="Item not found",
            headers={"X-Error": "There Goes my error"},
        )
    return {"item": items[item_id]}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

 

访问一个错误的url

http://127.0.0.1:8000/items-header/asda

1.png

查看Headers,发现多了X-Error

 1.png

自定义返回HTTPException

类似之前Bottle我们通过添加一个自定义的全局的错误,来统一的处理返回。FastAPI其实也提供一个自定义错误的机制:

官方示例如下:

import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name

app = FastAPI()

@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return jsONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
    )

@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

 

观察请求结果:

http://127.0.0.1:8000/unicorns/yolo

 

1.png

 当请求name == yolo的时候,我们主动抛出了UnicornException,而且我们,@app.exception_handler(UnicornException)也捕获到相关的异常信息,且返回了相关的信息。

 

覆盖FastAPI默认的异常处理

按官方文档说明就是,当请求包含无效的数据的时候,或参数提交异常错误的时候,会抛出RequestValidationError,

那其实我也可以通过上面的自定义异常的方式来覆盖重写我们的RequestValidationError所返回信息:

如: 默认代码没有添加覆盖处理的话: 发生异常的时候是提示是:

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

# @app.exception_handler(RequestValidationError)
# async def validation_exception_handler(request, exc):
#     return JSONResponse({'mes':'触发了RequestValidationError错误,,错误信息:%s 你妹的错了!'%(str(exc))})

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return {"item_id": item_id}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

发生异常的请求下返回:

http://127.0.0.1:8000/items/yolo

1.png

 

 恢复覆盖的时候:

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse({'mes':'触发了RequestValidationError错误,,错误信息:%s 你妹的错了!'%(str(exc))})

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return {"item_id": item_id}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

请求结果:

1.png

上面的返回其实我们还可以修改一下返回如下,指定响应码:

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Request,status
from fastapi.encoders import jsonable_encoder

app = FastAPI()

@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        # 注意fastapi包中的HTTPException才可以定义请求头
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return {"item_id": item_id}

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

 

再次请求一下

1.png

 可以发现状态码是指定的422,返回信息也是指定的。

 

本文参考链接:

http://www.zyiz.net/tech/detail-119883.html


--结束END--

本文标题: FastAPI--错误处理(5)

本文链接: https://www.lsjlt.com/news/193715.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • FastAPI--错误处理(5)
    HTTPException异常抛出再之前Bottle 中其实有一个就是HttpError异常类,在FastAPI也存在这么一个HTTPException。比如:import uvicorn from fastapi&nb...
    99+
    2023-01-31
    错误 FastAPI
  • FastAPI--跨域处理(7)
    为啥需要跨域处理,通常我们的API一般是给到前端去调用,但是前端可能使用域名和没提供的API域名是不一样,这就引发了浏览器同源策略问题,所以我们需要做跨域请求支持。FastAPI支持跨域的话,可以通过添加中间的形式,和bottle也有相似之...
    99+
    2023-01-31
    FastAPI
  • MySQL错误处理--1146错误
    在MySQL的主从复制过程中,出现了1146错误。提示的错误原因是:在默认的数据中找不到指定的表。show slave status\G;现实的同步状态。Slave_IO_Running: YESSlave...
    99+
    2022-10-18
  • qt 5 数据库错误
    1、编译程序遇到错误 :/usr/bin/ld: cannot find -lGL        解决办法:sudo apt-get install libglu1-...
    99+
    2022-10-18
  • Ant Design Pro 5 网络请求和错误处理是怎样的
    本篇文章为大家展示了Ant Design Pro 5 网络请求和错误处理是怎样的,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Ant Design Pro 5 的网络请求有点复杂,只看文档不阅读源码...
    99+
    2023-06-26
  • Python 错误处理
    1.1   错误处理1.1.1   try>>> try:...    print('try...')...    r = 10 / 0...    print('result:', r)... except ZeroDi...
    99+
    2023-01-31
    错误 Python
  • Python 6.1 错误处理
    错误处理在程序运行过程中,如 果发生了错误,可以事先约定返回一个错误代码,这样,就知道是否有错以及出错原因。在操作系统提供的调用中,返回错误代码非常常见。比如打开文件的open()函数,成功时返回文件描述符(就是一个整数),出错时返回-1....
    99+
    2023-01-31
    错误 Python
  • dos命令或批处理发生系统错误5拒绝访问怎么办
    这篇文章给大家分享的是有关dos命令或批处理发生系统错误5拒绝访问怎么办的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。win7在dos下运行net start mysql 不能启动mysql!提示发生系统错误 5...
    99+
    2023-06-08
  • ORACLE 异常错误处理
    即使是写得最好的PL/SQL程序也会遇到错误或未预料到的事件。一个优秀的程序都应该能够正确处理各种出错情况,并尽可能从错误中恢复。任何ORACLE错误(报告为ORA-xxxxx形式的Oracle错误号)、P...
    99+
    2022-10-18
  • python中的错误处理
    用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错: def foo(): r = some_function() if r...
    99+
    2022-06-04
    错误 python
  • ORACLE ORA-03137错误处理
    问题背景:        今天公司的OA系统运行的时候,用户反馈有时候登陆到OA平台会显示登陆不了。OA管理员检查发现应用没有问题,但是连接到数据库的时候有时候会...
    99+
    2022-10-18
  • cdn错误如何处理
    dn出现502错误的解决方法CDN加速出现502错误,一般是SSL证书错误,可以在网站面板中删除SSL证书后重新添加。或修改本地HOST到服务器ip地址测试。如果检查配置全部都正确的话,就是服务器营运商拦截了。所以网站在工信部备案后,还需要...
    99+
    2022-10-07
  • ASP.NETCore处理错误环境
    1.前言 ASP.NET Core处理错误环境区分为两种:开发环境和非开发环境。 开发环境:开发人员异常页。非开发环境:异常处理程序页、状态代码页。 在Startup.Configu...
    99+
    2022-11-13
  • python 错误处理:try..exc
    python错误继承表:https://docs.python.org/3/library/exceptions.html#exception-hierarchy格式:def 函数():      try:               内容...
    99+
    2023-01-31
    错误 python exc
  • 【故障处理】ORA-12162 错误的处理
    【故障处理】ORA-12162: TNS:net service name is incorrectly specified   一.1  场景 今天拿到一个新的环境,可是执行sq...
    99+
    2022-10-18
  • 操作系统错误5:拒绝访问
    SQLServer2012附件数据是只读模式,修改为读写模式报错: 把数据文件和日志文件的权限修改下: 不再报错。 ...
    99+
    2022-10-18
  • java错误:不支持发行版本5
    问题描述: 在idea中创建一个Maven项目,运行项目时报:java: 错误: 不支持发行版本 5! 打开Project Structure ,查询Modules的项目jdk版本,发现项目中所有的模块的都变成了5了。 打开File -...
    99+
    2023-08-19
    java maven intellij-idea
  • JavaScript中怎么处理错误
    这篇文章主要为大家展示了“JavaScript中怎么处理错误”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“JavaScript中怎么处理错误”这篇文章吧。Dem...
    99+
    2022-10-19
  • photoshop cs3错误处理办法
    安装好photoshop cs3后出现C:\Program Files\Common Files\Adobe\Adobe Version Cuecs3\Client\3.0.0\VersionCueUI.DLL错误解决方案!处理办法: 把目...
    99+
    2023-01-31
    错误 办法 photoshop
  • 如何处理Golang的错误
    Golang是一种强类型、面向对象的开发语言,因其高效性和并发性而备受推崇。在使用Golang开发过程中,经常会遇到返回错误的情况,因此我们需要学会如何处理Golang的错误。Golang中的错误类型在Golang中,错误类型属于内置类型之...
    99+
    2023-05-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作