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": "必填项不能为空"})
标签:code,return,处理,fastapi,request,item,items,异常,id
From: https://www.cnblogs.com/wengzx/p/16920498.html