Охватываемые темы: Базовое использование, Коды статуса, Детали ошибки, Кастомные заголовки.
Базовое использование
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
task = db.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="Задача не найдена")
return task
Коды статуса
from fastapi import HTTPException
from starlette import status
raise HTTPException(status_code=400, detail="Неверный запрос")
raise HTTPException(status_code=401, detail="Не аутентифицирован")
raise HTTPException(status_code=403, detail="Доступ запрещён")
raise HTTPException(status_code=404, detail="Не найдено")
raise HTTPException(status_code=422, detail="Ошибка валидации")
# Или через константы
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
Детали ошибки
raise HTTPException(
status_code=400,
detail={
"error": "validation_error",
"field": "title",
"message": "Заголовок не может быть пустым",
}
)
Кастомные заголовки
raise HTTPException(
status_code=401,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
Кастомный обработчик исключений
from fastapi import Request
from fastapi.responses import JSONResponse
class AppException(Exception):
def __init__(self, message: str, code: str):
self.message = message
self.code = code
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
return JSONResponse(
status_code=400,
content={"error": exc.code, "message": exc.message},
)
# Использование
raise AppException(message="Задача не найдена", code="task_not_found")
Обработчик 404 для всего приложения
from fastapi.responses import JSONResponse
@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
return JSONResponse(
status_code=404,
content={"message": "Ресурс не найден"},
)
💬 Комментарии (0)
Комментариев пока нет
Станьте первым, кто поделится мнением об этой статье!