JAVA
[JAVA] - Exception을 Custom하여 사용해보기
nam_ji
2024. 8. 4. 20:05
Custom Exception 사용해보기
Custom Exception 사용 이유
- 상세한 예외 정보를 제공할 수 있습니다.
- 코드 중복을 방지하고 ErrorCode를 한 곳에서 관리할 수 있습니다.
- Enum과 함께 사용하여 예외에 대한 응집도를 높일 수 있습니다.
- @ControllerAdvice, @RestControllerAdvice에서 해당 Custom Exception에 대한 자세한 후처리가 가능합니다.
ErrorCode
- 사용할 ErrorCode를 정의합니다.
-
package com.namji.datacollection.exception; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.http.HttpStatus; @Getter @AllArgsConstructor public enum ErrorCode { SUCCESS(HttpStatus.OK, "OK"), DUPLICATE_DEVICE(HttpStatus.BAD_REQUEST, "동일한 장치가 존재합니다."), DUPLICATE_GROUP(HttpStatus.BAD_REQUEST, "동일한 그룹이 존재합니다."); private final HttpStatus httpStatus; private final String message; }
-
CustomException
- ErrorCode를 담을 클래스를 생성합니다.
- RuntimeException을 상속 받고, ErrorCode 속성을 추가합니다.
-
package com.namji.datacollection.exception; import lombok.AllArgsConstructor; import lombok.Getter; import org.springframework.http.HttpStatus; @Getter @AllArgsConstructor public class CustomException extends RuntimeException { private ErrorCode errorCode; }
-
ErrorResponse
- Custom Error 내용을 담을 Response를 생성합니다.
-
package com.namji.datacollection.exception; import lombok.Builder; import lombok.Getter; import org.springframework.http.ResponseEntity; @Getter @Builder public class ErrorResponse { private int status; private String name; private String message; public static ResponseEntity<ErrorResponse> toResponseEntity(ErrorCode errorCode) { return ResponseEntity .status(errorCode.getHttpStatus()) .body(ErrorResponse.builder() .status(errorCode.getHttpStatus().value()) .name(errorCode.name()) .message(errorCode.getMessage()) .build()); } }
- toResponseEntity(ErrorCode e)로 Custom Error 내용을 작성하여 Response를 반환합니다.
-
GlobalCustomException
- Controller 전역에서 발생하는 Custom Error를 잡아줄 Handler를 생성합니다.
-
package com.namji.datacollection.exception; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalCustomException { @ExceptionHandler(CustomException.class) protected ResponseEntity<ErrorResponse> handleCustomException(CustomException e) { return ErrorResponse.toResponseEntity(e.getErrorCode()); } }
- @ControllerAdvice
- 모든 @Controller 즉, 전역에서 발생할 수 있는 예외를 잡아 처리합니다.
- @ExceptionHandler(CustomException.class)
- 발생한 CustomException 예외를 잡아서 하나의 메서드에서 공통으로 처리합니다.
- @ControllerAdvice + @ExceptionHandler
- 모든 컨트롤러에서 발생하는 CustomException을 처리합니다.
-
사용
- Controller에서 Request를 받아 그룹이 존재하는지 체크합니다.
- 만약 존재한다면 CustomException의 DUPLICATE_GROUP 예외를 발생시키켜 Response를 클라이언트에게 보냅니다.
-
Group findGroup = groupRepository.findByStationGroupSerial(groupRequest.getStationGroupSerial()); if (findGroup != null) { throw new CustomException(ErrorCode.DUPLICATE_GROUP); }
-
- Postman 테스트 결과