diff --git a/src/main/java/com/vmis/interfaceapp/config/GlobalExceptionHandler.java b/src/main/java/com/vmis/interfaceapp/config/GlobalExceptionHandler.java new file mode 100644 index 0000000..50df5dd --- /dev/null +++ b/src/main/java/com/vmis/interfaceapp/config/GlobalExceptionHandler.java @@ -0,0 +1,109 @@ +package com.vmis.interfaceapp.config; + +import com.vmis.interfaceapp.model.common.Envelope; +import com.vmis.interfaceapp.util.ExceptionDetailUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** + * 전역 예외 처리 핸들러 + * + *

컨트롤러에서 발생하는 모든 예외를 중앙에서 처리하여 일관된 에러 응답을 제공합니다.

+ */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * RuntimeException 처리 + * + *

서비스 레이어에서 발생한 RuntimeException을 잡아서 + * ExceptionDetailUtil로 포맷팅된 에러 메시지를 반환합니다.

+ * + * @param e RuntimeException + * @return 에러 메시지를 포함한 ResponseEntity + */ + @ExceptionHandler(RuntimeException.class) + public ResponseEntity handleRuntimeException(RuntimeException e) { + // ExceptionDetailUtil을 사용하여 에러 메시지 포맷팅 + String detail = ExceptionDetailUtil.buildForLog(e); + + log.error("[GLOBAL-ERROR] RuntimeException 발생: {}", detail, e); + + // 에러 응답 생성 + ErrorResponse errorResponse = new ErrorResponse( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + "Internal Server Error", + detail + ); + + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(errorResponse); + } + + /** + * 기타 모든 예외 처리 + * + * @param e Exception + * @return 에러 메시지를 포함한 ResponseEntity + */ + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e) { + String detail = ExceptionDetailUtil.buildForLog(e); + + log.error("[GLOBAL-ERROR] Exception 발생: {}", detail, e); + + ErrorResponse errorResponse = new ErrorResponse( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + "Internal Server Error", + detail + ); + + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(errorResponse); + } + + /** + * 에러 응답 DTO + */ + public static class ErrorResponse { + private int status; + private String error; + private String message; + + public ErrorResponse(int status, String error, String message) { + this.status = status; + this.error = error; + this.message = message; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +}