PHpullh
학습 라이브러리/Java/예외 계층 설계

JAVA · 예외처리

예외 계층 설계

애플리케이션의 예외 계층을 체계적으로 설계하는 방법입니다.

예외처리중급예외계층BusinessException에러코드설계

핵심 설명

애플리케이션의 예외 계층을 체계적으로 설계하는 방법입니다.

Java code

// 기본 비즈니스 예외
abstract class BusinessException extends RuntimeException {
    private final String errorCode;

    BusinessException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    BusinessException(String errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    String getErrorCode() { return errorCode; }
}

// 도메인별 예외 계층
class UserException extends BusinessException {
    UserException(String code, String msg) { super(code, msg); }
}

class UserNotFoundException extends UserException {
    UserNotFoundException(String userId) {
        super("USER_NOT_FOUND", "사용자를 찾을 수 없습니다: " + userId);
    }
}

class DuplicateUserException extends UserException {
    DuplicateUserException(String email) {
        super("USER_DUPLICATE", "이미 존재하는 이메일: " + email);
    }
}

// 사용
class UserService {
    void findUser(String id) {
        throw new UserNotFoundException(id);
    }

    public static void main(String[] args) {
        try {
            new UserService().findUser("123");
        } catch (UserNotFoundException e) {
            System.out.printf("[%s] %s%n", e.getErrorCode(), e.getMessage());
        } catch (BusinessException e) {
            System.out.println("비즈니스 에러: " + e.getMessage());
        }
    }
}

학습 팁

에러 코드를 예외에 포함하면 API 응답이나 로깅에서 일관된 에러 식별이 가능합니다.

주의할 점

예외 계층이 너무 깊으면 관리가 어렵습니다. 보통 2~3단계가 적당합니다. 과도한 세분화를 피하세요.

자주 묻는 질문

예외 계층 설계란 무엇인가요?

애플리케이션의 예외 계층을 체계적으로 설계하는 방법입니다.

예외 계층 설계 학습 시 주의할 점은 무엇인가요?

예외 계층이 너무 깊으면 관리가 어렵습니다. 보통 2~3단계가 적당합니다. 과도한 세분화를 피하세요.