TIL - 23.01.04

0

TIL

목록 보기
47/126

예외처리에 대해서는 그저 IllegalArgumentException를 사용해서 예를들어

User user = userRepository.findByUsername(username).orElseThrow(
                () -> new IllegalArgumentException("회원이름을 찾을 수 없습니다.")
        );

이런 식으로 작성하는 방법만 알고있었다.

하지만 에러를 처리하는 방법으로 따로 구현하여 프론트에서도 에러를 명확하게 알도록 하기위한 방법을 구현해보았다.

처음에 프로젝트에 적용을 해보았을 때는

@Getter
@Setter
public class RestApiException {
    private String errorMessage;
    private HttpStatus httpStatus;
}
@RestControllerAdvice
public class RestApiExceptionHandler {

    @ExceptionHandler(value = { IllegalArgumentException.class })
    public ResponseEntity<Object> handleApiRequestException(IllegalArgumentException ex) {
        RestApiException restApiException = new RestApiException();
        restApiException.setHttpStatus(HttpStatus.BAD_REQUEST);
        restApiException.setErrorMessage(ex.getMessage());

        return new ResponseEntity(
                restApiException,
                HttpStatus.BAD_REQUEST
        );
    }
}

이와같이 강의자료에 나와있는대로 일단 @Setter를 사용해보았다.

하지만 지금까지 여러번 들어왔던대로 Setter를 사용하지 않기 위해
RestApiException에 생성자를 만들고 RestApiExceptionHandler클래스에서 ResponseEntity로 들어가는 body에 값을 넣어주는 방법을 사용하였고,

추가로 우리는 프로젝트 요구사항으로 클라이언트에게 에러코드도 반환해야하기 때문에 private HttpStatus httpStatus가 아니라 private int errorCode로 변경하였다.

@Getter
public class RestApiException {
    private String errorMessage;
    private int errorCode;

    public RestApiException(String errorMessage, int errorCode) {
        this.errorMessage = errorMessage;
        this.errorCode = errorCode;
    }
}
public class RestApiExceptionHandler {
    @ExceptionHandler(value = {IllegalArgumentException.class})
    public ResponseEntity<Object> handleApiRequestException(IllegalArgumentException ex) {
        RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
                                                                // RestApiException에 생성자를 만들어서 Setter대신 값을 넣어줌
        return new ResponseEntity<>(
                restApiException, // ResponseEntity에 들어가는 body값
                HttpStatus.BAD_REQUEST // 포스트맨에 보이는 400 Bad request가 얘임
        );
    }
}

근데 여기서 의문점이 생긴게...
나는 평소에 어노테이션을 먼저 사용안하고 코드를 작성한다음 오류나 에러가 생기면 그 때 어노테이션을 써보면서 어노테이션의 중요성을 몸으로 이해하려는 편인데
깜빡하고 @ExceptionHandler(value = {IllegalArgumentException.class})에서 @ExceptionHandler만 작성했는데 실행했을 때 오류와 에러 둘 다 뜨지않았다.........
이거에 대해서는 조금더 공부해본 뒤 알아봐야겠당..ㅎ

0개의 댓글