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

RuntimeException

RuntimeException 을 extends 받는다.
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
}
@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/