- 1. FastAPI 입문: 설치부터 Hello World 까지
- 2. Path 와 Query 매개변수 (URL 로 데이터 받기)
- 3. Pydantic 으로 Request Body 다루기
- 4. Response Model 과 HTTP 상태 코드
- 5. 예외 처리 (HTTPException 완벽 가이드)
- 6. 의존성 주입 (Dependency Injection) 정복
- 7. SQLAlchemy 비동기 데이터베이스
- 8. JWT 인증과 보안 (로그인부터 토큰 갱신까지)
- 9. 실시간 통신 (WebSockets & SSE)
- 10. 테스트 작성법 (Pytest 완전 가이드)
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
```