fastapi异常处理
学习地址 http://www.360doc.com/content/22/1114/08/78594709_1055831061.shtml
DEMO
items={"test":"这是测试"}
@app.get("/item/{item_id}")
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]}
# 捕获参数异常
@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(request: Request, exc: RequestValidationError):
print(f"参数不对{request.method} {request.url}") # 可以用日志记录请求信息,方便排错
# return JSONResponse({"code": "400", "message": exc.errors()})
return JSONResponse({"code": "400", "msg": "必填项不能为空"})