예외처리 RuntimeException

yesrin·2023년 7월 26일

JPA

목록 보기
2/7

하위에 있는 예외 일수록 범위가 작다.
범위를 작게 만들어 주는것이 예외처리에 좋다.

Java의 예외 계층 구조

RuntimeException

예외처리를 Custom 해보자

RuntimeException 을 extends 받는다.

NotFoundException 생성

public class NotFoundException extends RuntimeException{

    public NotFoundException() {
    }

    public NotFoundException(String message) {
        super(message);
    }
}

GlobalExceptionHandler 에 추가

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({NotFoundException.class})
    public ResponseEntity<RestApiException> NotFoundException(NotFoundException ex) {
        RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }
}

사용예시

private Post findPost(Long postId) {
        return postRepository.findById(postId).orElseThrow(() ->
                new NotFoundException(
                        messageSource.getMessage(
                                "post.not.exist",
                                null,
                                "post does not exist",
                                Locale.getDefault()
                        )));
    }

messageSources는 다국어 처리를 위해 사용한다.

다국어처리가 필요하지 않다면 아래 형태의 이넘클래스를 만들어 사용해도 된다.

@Getter
public enum ErrorCode {

  INVALID_TOKEN(400, "토큰이 유효하지 않습니다."),
  UNAUTHORIZED_USER(400, "작성자만 수정/삭제 할 수 있습니다."),
  IN_USED_USERNAME(400, "중복된 username 입니다."),
  NOT_FOUND_USER(400, "회원을 찾을 수 없습니다."),
  NOT_FOUND_POST(400, "요청한 게시글이 존재하지 않습니다."),
  WRONG_PASSWORD(400, "비밀번호가 틀렸습니다."),
  NOT_FOUND_COMMENT(400, "작성한 댓글을 찾을 수 없습니다.");

  private int errorCode;
  private String errorMessage;

  ErrorCode(int errorCode, String errorMessage) {
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
  }
}

참고
https://rollbar.com/blog/java-exceptions-hierarchy-explained/

https://github.com/hwchoi96/sparta_lv3_baseline/blob/main/src/main/java/com/sparta/hanghaeblog/common/code/HanghaeBlogErrorCode.java

profile
안녕하세요! 틀린 정보는 댓글 달아 주세요.

0개의 댓글