런닝 코스 공유 서비스

[런닝 코스 공유 서비스] - 10. 공통 예외 처리

sson-coding 2025. 12. 21. 16:35

개발 요약

  • 에러 응답을 일관된 구조로 제공하기 위해 공통 예외 처리 구조 구현
  • 컨트롤러에서는 성공 응답만 책임지고, 에러 응답은 전역 예외 처리로 위임

개발 내용

1) BaseException

  • 모든 커스텀 예외의 부모 클래스
    • RuntimeException 으로 언체크 예외
    • ErrorCode 객체를 받아 예외를 구성
/**
 * 모든 커스텀 예외의 부모 클래스
 */
public class BaseException extends RuntimeException {

	private final ErrorCode errorCode;

	public BaseException(ErrorCode errorCode) {
		super(errorCode.getMessage());
		this.errorCode = errorCode;
	}

	public ErrorCode getErrorCode() {
		return errorCode;
	}
}

2) ErrorCode

  • 에러 코드의 형식 통일을 위한 규칙서
    • HttpStatus : HTTP 상태 코드
    • code : 에러 식별자
    • message : 클라이언트에게 전달할 메시지
  • 모든 도메인 에러 코드는 이 인터페이스를 구현해야 함
    • UserErrorCode, CourseErrorCode 등
  • CommonErrorCode
    • 공통 에러들을 정의
/**
 * 에러 코드의 형식 통일을 위한 인터페이스
 */
public interface ErrorCode {
	int getStatus();
	String getCode();
	String getMessage();
}

3) GlobalExceptionHandler

  • BaseException, Exception 등 에러가 발생했을 때 , 이 클래스에서 전역으로 처리하여 일관성 있는 응답 반환
/**
 * @RestController 로 선언한 지점에서 발생한 에러를 도중에
 * @RestControllerAdvice 로 선언한 클래스 내에서 캐치하여
 * Controller 내에서 발생한 에러를 처리
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	
	@ExceptionHandler(BaseException.class)
	public ResponseEntity<ErrorResponse> handleBaseException(BaseException ex){
		ErrorCode errorCode = ex.getErrorCode();
		return ResponseEntity
			.status(errorCode.getStatus())
			.body(new ErrorResponse(errorCode.getStatus(), errorCode.getCode(), errorCode.getMessage()));
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity<ErrorResponse> handleException(Exception ex){
		ErrorCode errorCode = CommonErrorCode.INTERNAL_SERVER_ERROR;
		return ResponseEntity
			.status(errorCode.getStatus())
			.body(new ErrorResponse(errorCode.getStatus(), errorCode.getCode(), errorCode.getMessage()));
	}
}

4) ErrorResponse

  • 에러 발생 시 원인을 빠르게 식별할 수 있도록 설계
  • HTTP Status : 프로토콜 관점에서 어떤 결과로 처리되었는지를 나타냄
  • code : 애플리케이션 내부의 비즈니스 오류를 식별
/**
 * 에러 발생 시 클라이언트에게 반환되는 공통 에러 응답 객체
 */
@Getter
public class ErrorResponse{
	private int status;
	private String code;
	private String message;

	public ErrorResponse(int status, String code, String message) {
		this.status = status;
		this.code = code;
		this.message = message;
	}
}

참고자료

https://adjh54.tistory.com/79

https://ddururiiiiiii.tistory.com/690