오류 처리 구조 설계: 백엔드와 프론트엔드의 협업
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
웹 개발
대상자
- 백엔드 개발자: FastAPI 기반의 오류 처리 구조 설계
- 프론트엔드 개발자: React 기반의 오류 유형 매핑 및 UI 구현
- 중간/고급 개발자: 복잡한 시스템에서의 오류 분리 패턴 이해
- 난이도: 중급 이상 (오류 처리 패턴, 타입 시스템 활용)
핵심 요약
- ErrorType enum을 통해 오류 유형을 명확하게 정의하고, ApplicationError 클래스로 상태 코드와 메시지를 통합
- FastAPI의 예외 처리기(application_error_handler)를 통해 오류 처리 중복 제거
- ApiClient에서 백엔드 오류 유형을 ApiError 인터페이스로 매핑하고, ActionRequiredError와 같은 컴포넌트를 통해 사용자 상호작용 유도
섹션별 세부 요약
1. 기존 오류 처리 방식의 한계
- 스파게티 코드 발생: 상태 코드만 사용하거나 200 OK +
is_success
플래그 사용 - 복잡한 예외 처리: 각 오류 유형별
try-except
블록으로 인한 코드 중복 - 예시:
```python
@auth_router.post("/register")
async def register(...):
try:
result = await auth_controller.register(data)
except CustomException_1 as exc:
...
```
2. 백엔드 오류 처리 구조 설계
- ErrorType enum 정의:
```python
class ErrorType(StrEnum):
unauthorized = "unauthorized"
bad_request = "bad_request"
user_exists = "user_exists"
```
- ApplicationError 클래스:
```python
class ApplicationError(Exception):
message: str
code: int
error_type: ErrorType
```
- application_error_handler 예외 처리기:
```python
async def application_error_handler(req: Request, exc: ApplicationError):
return JSONResponse({"detail": exc.text, "error_type": exc.error_type}, status_code=exc.code)
```
3. 프론트엔드 오류 매핑 구현
- ApiError 인터페이스 정의:
```typescript
export interface ApiError {
message: string;
code: number;
error_type: ErrorTypes;
}
```
- ApiClient에서 오류 처리:
```typescript
private async callApi(...) {
try {
return await this.client.request(...);
} catch (error) {
throw {
message: errorMessage,
code: errorCode,
error_type: error_type,
} as ApiError;
}
}
```
- ErrorFactory를 통해 오류 유형을 UI 컴포넌트 매핑:
```typescript
class ErrorFactory {
private static errorMapping: Record
unauthorized: UnauthorizedError,
bad_request: BadRequestError,
...
}
}
```
4. 사용자 경험 중심의 오류 UI 구현
- CommonError와 ActionRequiredError 클래스로 오류 유형 구분:
```typescript
export class SubscriptionError extends ActionRequiredError {
protected defaultData: DefaultActionProps = {
title: "Action is Not Allowed",
message: "You don't have an active subscription.",
href: "/prices",
buttonText: "Subscribe",
};
}
```
- 모달 UI로 오류 표시:
```typescript
{error && ErrorFactory.getErrorComponent(error.error_type, openError, () => setOpenError(false))}
```
결론
- ErrorType enum과 ApplicationError를 통해 오류 유형을 명확히 분리하고, FastAPI의 예외 처리기로 중복 제거
- ApiError 인터페이스와 ErrorFactory를 활용해 프론트엔드에서 오류 유형을 UI 컴포넌트로 매핑
- ActionRequiredError와 같은 상호작용 가능한 오류 UI를 통해 사용자 경험 향상
> 핵심 팁: 백엔드에서 ErrorType
을 정의하고, 프론트엔드에서 ErrorFactory
로 오류 유형을 매핑해 일관된 오류 처리 구조를 구축하세요.