diff --git a/src/main/java/com/mpnp/baechelin/exception/CustomException.java b/src/main/java/com/mpnp/baechelin/exception/CustomException.java new file mode 100644 index 0000000..e5a5387 --- /dev/null +++ b/src/main/java/com/mpnp/baechelin/exception/CustomException.java @@ -0,0 +1,13 @@ +package com.mpnp.baechelin.exception; + +import lombok.Getter; + +@Getter +public class CustomException extends RuntimeException{ + private ErrorCode errorCode; + + public CustomException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/src/main/java/com/mpnp/baechelin/exception/ErrorResponse.java b/src/main/java/com/mpnp/baechelin/exception/ErrorResponse.java new file mode 100644 index 0000000..869bc19 --- /dev/null +++ b/src/main/java/com/mpnp/baechelin/exception/ErrorResponse.java @@ -0,0 +1,29 @@ +package com.mpnp.baechelin.exception; + +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.ResponseEntity; + +import java.time.LocalDateTime; + +@Getter +@Builder +public class ErrorResponse { + private final LocalDateTime timestamp = LocalDateTime.now(); + private final int status; + private final String error; + private final String code; + private final String message; + + public static ResponseEntity toResponseEntity(ErrorCode errorCode) { + return ResponseEntity + .status(errorCode.getStatus()) + .body(ErrorResponse.builder() + .status(errorCode.getStatus()) + .error(errorCode.getCode()) + .code(errorCode.name()) + .message(errorCode.getMessage()) + .build() + ); + } +} diff --git a/src/main/java/com/mpnp/baechelin/exception/GlobalExceptionHandler.java b/src/main/java/com/mpnp/baechelin/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..7fb8076 --- /dev/null +++ b/src/main/java/com/mpnp/baechelin/exception/GlobalExceptionHandler.java @@ -0,0 +1,17 @@ +package com.mpnp.baechelin.exception; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + @ExceptionHandler(value = CustomException.class) + protected ResponseEntity handleCustomException(CustomException e) { + log.error("handleCustomException throw CustomException : {}", e.getErrorCode()); + return ErrorResponse.toResponseEntity(e.getErrorCode()); + } +}