[FastAPI Docs] Handling Erros

JeongChaeJin·2022년 9월 1일
0

Use HTTPException

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]}
  • HTTPException은 python normal exception이다.
{
  "detail": "Item not found"
}
  • 에러 발생 시 자세한 Json 로그를 남길 수 있다.
  • dict, list를 pass해서 JSON을 더 풍부하게 보여주는 것도 좋은 Tip이다.

Add custom headers

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]}
  • 커스텀 헤더를 통핸 에러를 처리하면 유용한 경우들이 있다.

profile
OnePunchLotto

0개의 댓글