Exception ver.2

강민형·2020년 11월 9일
1
post-thumbnail

Exception

Exception 적용을 하다 보니 좋은 블로그 글이 있어서 다시 한번 적용해봄
https://cheese10yun.github.io/spring-guide-exception/#null

기존 코드는 리턴값을 Map 형태로 만들어야 했기에 안에 들어가는 키값을 일일히 선언해줘야하고
그 안에 값들이 있는지 직관적으로 파악하기 어려운 부분이 있었음
또한 Exception들만 따로 모아서 관리하는 것이 아닌 해당 컨트롤러 안에서 만든것이기 때문에
관리하기가 어렵다

적용방법

Exception들을 관리하는 핸들러를 먼저 만들어주었음

@RestControllerAdvice
public class ExceptionHandlers {
    @ExceptionHandler(ConstraintViolationException.class)
    ResponseEntity<ErrorResponse> handleConstraintViolationException(ConstraintViolationException e) {
        final ErrorResponse response = ErrorResponse.of(ErrorCode.MEMID_NOT_FOUNDED);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
    
    ...
}

이렇게 핸들러로 관리하게 되면 프로젝트 안에 모든 Exception을 한곳에서 관리해 편해진다

그 다음 리턴할 ResponseEntity에 담아줄 ErrorResponse 객체를 만들준다

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ErrorResponse {

    private String message;
    private int status;
    private String code;

    private ErrorResponse(final ErrorCode code) {
        this.message = code.getMessage();
        this.status = code.getStatus();
        this.code = code.getCode();
    }

    public static ErrorResponse of(final ErrorCode code) {
        return new ErrorResponse(code);
    }

}

출처 블로그에는 ErrorList에 대한 값도 함께 담아주었지만 일단 난 빼고 진행할거임. 암튼 그럼

마지막으로 enum을 만들어 각 CASE에 대한 값을 지정해 넣어준다.
아직 enum이 익숙하진 않아서 정확히 이해하진 못했지만 사내 코드에 enum을 많이 쓰고있고
이렇게 사용해보니 활용도가 매우 높다고 생각해서 공부할 필요성을 느낀다.

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ErrorCode {
    MEMID_NOT_FOUNDED(400, "member.memId", "memId는 반드시 입력되어야 합니다."),
    MEMID_OR_MEMBERCODE_NOT_FOUNDED(400, "member.memId || member.memberCode", "memId와 memberCode는 반드시 입력되어야 합니다."),
    NO_RESULT(500, "member.memId || member.memberCode", "조회된 결과가 없습니다. 입력값을 확인해 주세요")
    ;

    private final String code;
    private final String message;
    private final int status;

    ErrorCode(final int status, final String code, final String message) {
        this.status = status;
        this.message = message;
        this.code = code;
    }

    public String getMessage() {
        return this.message;
    }

    public String getCode() {
        return code;
    }

    public int getStatus() {
        return status;
    }
}

결과

profile
Since 2020.11.02 / BackEnd Developer / SSAFY 3기

0개의 댓글