SpringBoot Exception 처리3 - enum 적용

https://velog.io/@mooh2jj/SpringBoot-Exception-처리2 외에
Exception 처리에 대해서 customize한 Excetption 클래스들을 소개합니다. enum을 추가해서 더 정리가 쉽게 되었습니다.


ErrorDetails

@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ErrorDetails {

    private Date timestamp;
    private String message;
    private String description;
    // enum 추가
    private BlogErrorCode errorCode;
}

BlogErrorCode

ErrorCode를 열거형으로 묶어서 정리할 수 있습니다.

@Getter
@AllArgsConstructor
public enum BlogErrorCode {

    NO_TARGET("해당되는 대상이 없습니다."),
    DUPLICATED_ID("Id가 중복되어 있습니다."),

    INTERNAL_SERVER_ERROR("서버에 오류가 발생했습니다."),
    INVALID_REQUEST("잘못된 요청입니다.")
    ;

    private final String message;

}

RuntimeException 상속한 커스터마이징한 Exception들

1) ResourceNotFoundException(NotFount용 Exception)

@Getter
public class ResourceNotFoundException extends RuntimeException{

    private BlogErrorCode errorCode;
    private String detailMessage;

    public ResourceNotFoundException(BlogErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
        this.detailMessage = errorCode.getMessage();
    }

}

2) BlogAPIException

@Getter
public class BlogAPIException extends RuntimeException {

    private HttpStatus status;

    private BlogErrorCode errorCode;

    public BlogAPIException(BlogErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
        this.message = errorCode.getMessage();
    }

}

ExceptionHandler

BlogExceptionHandler

Specific: @ExceptionHandler에서 특정 Exception 클래스를 골라주면 됩니다.
Gloabl : @ExceptionHandler에서 Exception 클래스만 골라주면 됩니다.

✅Exception 처리2 에서 다른 점은 ErrorDetails 안에 에러코드를 열거형으로 묶어든 enum을 장착한다는 것입니다.

@ControllerAdvice
public class BlogExceptionHandler extends ResponseEntityExceptionHandler {

   // handle sepecific exceptions
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorDetails> handleResourceNotFoundException(
            ResourceNotFoundException exception,
            WebRequest webRequest){

        ErrorDetails errorDetails = ErrorDetails.builder()
                .timestamp(new Date())
                .message(exception.getMessage())
                .description(webRequest.getDescription(false))
                .errorCode(exception.getErrorCode())
                .build();

        return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(BlogAPIException.class)
    public ResponseEntity<ErrorDetails> handleBlogAPIException(
            BlogAPIException exception,
            WebRequest webRequest){

        ErrorDetails errorDetails = ErrorDetails.builder()
                .timestamp(new Date())
                .message(exception.getMessage())
                .description(webRequest.getDescription(false))
                .errorCode(exception.getErrorCode())
                .build();

        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }

 	// global exception
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorDetails> handleGlobalException(
            Exception exception,
            WebRequest webRequest){

        ErrorDetails errorDetails = ErrorDetails.builder()
                .timestamp(new Date())
                .message(exception.getMessage())
                .description(webRequest.getDescription(false))
                .errorCode(INTERNAL_SERVER_ERROR)
                .build();

        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

BlogServiceImpl

	// Exception 처리 메서드
    private Comment errorCheckComment(BoardRepository boardRepository, Long boardId, CommentRepository commentRepository, Long commentId) {
        Board board = boardRepository.findById(boardId)
                .orElseThrow(() -> new ResourceNotFoundException(BlogErrorCode.NO_TARGET));

        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new ResourceNotFoundException(BlogErrorCode.NO_TARGET));

        if (!comment.getBoard().getId().equals(board.getId())) {
            throw new BlogAPIException(BlogErrorCode.NO_TARGET);
        }
        return comment;
    }


참고

좋은 웹페이지 즐겨찾기