锵锵枪 wrote:
使用FastAPI搭建网站(五):异常处理 这篇算这个系列的完结篇,总结下自己最近的使用FastAPI遇到的一些问题。 ###返回异常 通过 HTTPException 这个类,FastAPI 可以非常容易的向客户端返回错误信息。 ![](https://wx4.sinaimg.cn/large/6cd6d028ly1ff9l79kjt1j20go0a0t8y.jpg) ``` from fastapi import FastAPI, HTTPException app = FastAPI() items = {"apple": "red apple"} @app.get("/items/{id}") async def read_item(item_id: str): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") ``` ###自定义异常页面 在前后端分离的架构中,前端只需要获取后端的错误代码即可。但是在传统的MVC模型下,前端页面的生成是在服务端完成。为了有更好的体验,我们可以通过app的 exception_handler 方法,自定义错误页面。 #####参数错误 FastAPI强大的功能就是数值验证,通过 handler RequestValidationError,可以对请求参数类错误进行自定义返回页面。 ``` from fastapi.exceptions import RequestValidationError app = FastAPI(openapi_url=None) ... @app.exception_handler(RequestValidationError) async def validation_exception_handler(request, exc): return t.TemplateResponse("error.html",{"request": request, "title": '请求参数错误'},status_code=422) ``` #####其余HTTP错误 程序中通过 HTTPException 抛出的错误信息,我们可以通过 handler starlette 的 HTTPException 来自定义对应的返回页面。 Tips: FastAPI大多数方法都直接继承于Starlette,但是FastAPI的 HTTPException 类进行了一些自定义方法。所以要捕获HTTP错误的时候,不得不使用Starlette的 HTTPException。相信在后续的一些版本,应该会进行一些改进,比如换个名字? ``` from starlette.exceptions import HTTPException as StarletteHTTPException ... @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): return t.TemplateResponse("error.html", {"request": request, "title": exc.detail},status_code=exc.status_code)#exc.status_code ``` 这样当有错误抛出的时候,就可以通过个性化的页面展示给浏览器了。
锵锵枪 2020-08-22 22:33:18  0 回复