상세 컨텐츠

본문 제목

[WithParents] 예외처리 | custom exception | RestControllerAdvice | ExceptionHandler

Project/WithParents

by yooputer 2022. 11. 16. 18:24

본문

이전 프로젝트에서 예외처리를 염두에 두지 않고 개발을 했더니 오류 처리할 때마다 개판이었다...(프론트야 미안해,,,)

그래서 이번 프로젝트는 꼭 예외처리를 위한 인프라를 만들어두고 개발을 하기로 했다

 

예외처리를 위해 RestControllerAdvice 클래스와 ExceptionHandler 메소드를 구현하고

커스텀예외클래스를 기반으로 예외처리할 것이다.


RestControllerAdvice 생성

컨트롤러에서 발생하는 예외를 처리하는 ApiExceptionHandler 클래스를 생성한다

@RestControllerAdvice
public class ApiExceptionHandler {

}

ErrorResponse 정의

ErrorResponse는 예외를 반환할 때 사용하는 엔티티이다.

@Data
@Builder
public class ErrorResponse {

    private HttpStatus status;
    private String type;
    private String message;

}

custom exception 정의

특정 상황에 던질 custom exception을 구현한다.

@RequiredArgsConstructor
@Getter
public class InvalidUserIdException extends RuntimeException{

    private HttpStatus status = HttpStatus.BAD_REQUEST;
    private final Long userId;

    public String getMessage(){
        return "id가 "+id+"인 사용자가 존재하지 않습니다.";
    }

    public static ErrorResponse toErrorResponse(InvalidUserIdException e){
        return ErrorResponse.builder()
                .status(e.getStatus())
                .type(InvalidUserIdException.class.getSimpleName())
                .message(e.getMessage())
                .build();
    }

}

InvalidUserIdException은 주어진 id에 해당하는 user가 없는 경우 발생하는 예외이므로

예외메시지에 userId를 포함하고 싶어서 userId라는 속성을 추가했다.


ExceptionHandler 구현

ApiExceptionHandler 클래스에 다음과같이 InvalidUserIdException을 처리하는 메서드를 작성한다.

@ExceptionHandler(value = {InvalidUserIdException.class})
public ResponseEntity<ErrorResponse> InvalidUserIdException(InvalidUserIdException e){
    return ResponseEntity
            .status(e.getStatus())
            .body(InvalidUserIdException.toErrorResponse(e));
}

기존 코드 수정

기존 UserService의 코드를 다음과 같이 수정했다.


사담

하나의 custom exception과 오류코드 enum을 통해 예외처리하는 방법과

여러개의 custom exception으로 예외처리하는 방법 중 고민했는데 

클린코드에서 오류코드말고 예외클래스로 오류처리하라고 해서 후자를 선택했다. 전자의 방법이 더 쉽다... 상당히 고민했다...

근데 이렇게 하는거 맞나 싶다...?

관련글 더보기