5. 예외 처리 (HTTPException 완벽 가이드)

# 5 강. 예외 처리 (HTTPException) ## 🎯 학습 목표 - HTTPException 기본 사용법 - 커스텀 예외 클래스 - 전역 예외 처리기 --- ## 1. HTTPException 기본 ```python from fastapi import HTTPException @app.get("/items/{id}") def get_item(id: int): if id not in items_db: raise HTTPException(status_code=404, detail="Item not found") return {"item": items_db[id]} ``` --- ## 2. 커스텀 예외 클래스 ```python class NotFoundException(HTTPException): def __init__(self, resource: str, id: int): super().__init__( status_code=404, detail=f"{resource} {id} not found" ) @app.get("/users/{id}") def get_user(id: int): user = db.get(id) if not user: raise NotFoundException("User", id) return user ```