[python] FastAPI에서 예외 처리하기

FastAPI는 빠르고 간편한 API 개발을 위한 프레임워크로서, 예외 처리를 효과적이고 간편하게 제공합니다. 예외 처리는 API에서 발생할 수 있는 잠재적인 문제를 다루고, 클라이언트에게 적절한 응답을 제공하는 역할을 합니다.

예외 처리 방법

FastAPI에서는 ExceptionHandler 클래스를 사용하여 예외 처리를 구현할 수 있습니다.

from fastapi import FastAPI
from fastapi.exception_handlers import (
    http_exception_handler,
    request_validation_exception_handler,
    server_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        status_code=422,
        content={"detail": str(exc)}
    )

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )

@app.exception_handler(Exception)
async def server_exception_handler(request, exc):
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )

위 코드에서는 RequestValidationError, HTTPException, 그리고 Exception 세 가지 예외에 대한 처리 함수를 정의하고 있습니다. 이 예외들은 각각 Request Validation 오류, HTTP 오류, 그리고 서버 오류를 나타내는 예외입니다.

각 예외에 대한 처리 함수는 JSONResponse를 반환합니다. 이를 통해 클라이언트에게 적절한 상태 코드와 응답 내용을 전달할 수 있습니다.

사용자 정의 예외

FastAPI에서는 사용자가 정의한 예외에 대해서도 예외 처리를 할 수 있습니다. 다음은 간단한 사용자 정의 예외 클래스의 예입니다.

class CustomException(Exception):
    def __init__(self, detail: str):
        self.detail = detail

사용자 정의 예외를 처리하기 위해서는 ExceptionHandler 클래스에 이 예외 클래스에 대한 처리 함수를 추가해야 합니다.

@app.exception_handler(CustomException)
async def custom_exception_handler(request, exc):
    return JSONResponse(
        status_code=400,
        content={"detail": exc.detail}
    )

이렇게 하면 CustomException 예외가 발생했을 때, 클라이언트에게 400 상태 코드와 예외의 상세 내용을 포함하는 응답을 전달할 수 있습니다.

참고 자료