Xử lý lỗi

Nhập môn FastAPI

Matt Eckerle

Software and Data Leader

Hai lý do chính để xử lý lỗi

Lỗi phía người dùng

  • URI không hợp lệ hoặc đã lỗi thời
  • Thiếu hoặc nhập sai đầu vào
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Return an error
    else:
        crud.delete_item(item)
        return {}

Lỗi phía máy chủ

  • Sự cố khác xảy ra
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
Nhập môn FastAPI

Mã trạng thái HTTP: “Mức độ cảnh báo”

  • Giúp API trả về trạng thái trong phản hồi
    • Thành công, thất bại, lỗi, v.v.
  • Mã cụ thể do giao thức HTTP định nghĩa
  • Phạm vi: 100 - 599
  • Phân loại theo chữ số đầu (1 -5)
  1. Phản hồi thông tin (100 - 199)
  2. Phản hồi thành công (200 - 299)
  3. Thông điệp chuyển hướng (300 - 399)
  4. Lỗi phía khách (400 - 499)
  5. Lỗi phía máy chủ (500 - 599)
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Nhập môn FastAPI

Mã trạng thái HTTP phổ biến

Thành công (200 - 299)

  • 200 OK
    • Mặc định khi thành công
  • 201 Created
    • Dùng cho POST
  • 202 Accepted
    • Chưa cam kết. “Đang xử lý”
  • 204 No Content
    • Thành công! Không có nội dung trả về

Phản hồi khác

  • 301 Moved Permantently
    • URI đã đổi vĩnh viễn
  • 400 Bad Request
    • Lỗi phía khách
  • 404 Not Found
    • Máy chủ không tìm thấy tài nguyên yêu cầu
  • 500 Internal Server Error
    • Máy chủ gặp tình huống không biết xử lý thế nào
Nhập môn FastAPI

Xử lý lỗi bằng mã trạng thái

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 {}
Nhập môn FastAPI

Vamos praticar!

Nhập môn FastAPI

Preparing Video For Download...