錯誤處理

FastAPI 入門

Matt Eckerle

Software and Data Leader

處理錯誤的兩大原因

使用者錯誤

  • URI 無效或已過期
  • 輸入遺漏或不正確
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Return an error
    else:
        crud.delete_item(item)
        return {}

伺服器錯誤

  • 發生了其他問題
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
FastAPI 入門

HTTP 狀態碼:『吼叫等級』

  • 讓 API 在回應中提供狀態
    • 成功、失敗、錯誤等
  • HTTP 通訊協定定義了特定代碼
  • 範圍:100 - 599
  • 依首位數分類(1 - 5
  1. 資訊回應(100 - 199
  2. 成功回應(200 - 299
  3. 重新導向(300 - 399
  4. 用戶端錯誤(400 - 499
  5. 伺服器錯誤(500 - 599
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
FastAPI 入門

常見 HTTP 狀態碼

成功(200 - 299

  • 200 OK
    • 預設成功回應
  • 201 Created
    • POST 專用
  • 202 Accepted
    • 尚未承諾。「正在處理」
  • 204 No Content
    • 成功!無其他內容

其他回應

  • 301 Moved Permantently
    • URI 已永久變更
  • 400 Bad Request
    • 用戶端錯誤
  • 404 Not Found
    • 找不到要求的資源
  • 500 Internal Server Error
    • 伺服器遇到無法處理的情況
FastAPI 入門

用狀態碼處理錯誤

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Send response with status 404 and specific error message
        raise HTTPException(status_code=404, detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}
FastAPI 入門

一起來練習吧!

FastAPI 入門

Preparing Video For Download...