@ControllerAdvice - Exception

ims·2020년 11월 14일
0

BlueDot-Spring

목록 보기
11/13

Handler 설명

즉, 스레드간의 통신을 위한 장치가 바로 핸들러(Handler)입니다

https://itpangpang.xyz/185

구조

  • Exception을 controller나 service단마다 배치할 수도 있지만, 그러면 유지보수가 힘들어진다.

  • 그래서 @ControllerAdvice를 달아주는 Handler에서 Exception들을 통합적으로 관리해준다.

Exception들을 handler에서 관리한다. 사용할 때는 Exception에 Error코드를 담아서 호출하면, handler에서 response를 통해 클라이언트한테 응답한다

코드

ErrorCode.java

@Getter
@AllArgsConstructor
public enum ErrorCode {

    ERROR_TEST_1(5000,"첫번째 에러야"),
    ERROR_TEST_2(1010,"두번째 에러야")
    ;

    private final int status;
    private final String message;

}
  • 먼저 에러코드를 선언해준다.

ErrorResponse.java

@Builder
@Getter
public class ErrorResponse {

    private final HttpStatus code;

    private final LocalDateTime timestamp;

    private final String message;

    private final int status;

}
  • Error에 대한 정보를 담을 Response DTO를 선언한다.

CustomException.java

public class CustomException extends RuntimeException{

    private final ErrorCode errorCode;

    public CustomException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode=errorCode;
    }
    public ErrorCode getErrorCode() {
        return errorCode;
    }
}
  • errorCode를 화면에 출력하고, errorCode값을 넣어준다.

ErrorNotFoundException.java

  • CustomException을 상속한다.

ErrorHandler.java

@ControllerAdvice
@ResponseBody
public class ErrorHandler {

    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    @ExceptionHandler(ErrorNotFoundException.class)
    public ErrorResponse handleNotFound(CustomException e){
            return ErrorResponse.builder()
                    .code(HttpStatus.BAD_REQUEST)
                    .message(e.getErrorCode().getMessage())
                    .status(e.getErrorCode().getStatus())
                    .timestamp(LocalDateTime.now())
                    .build();
    }
}

@ResponseBody

  • @Responsbody 를 붙여줘야 아래의 return 값만 client에게 전달된다.

    메소드에 @ResponseBody 로 어노테이션이 되어 있다면 메소드에서 리턴되는 값은 View 를 통해서 출력되지 않고 HTTP Response Body 에 직접 쓰여지게 됩니다.

안붙였을 시

@ResponseStatus

  • (HttpStatus.BAD_GATEWAY) = 502
    body형태로 return 되는 형태와 달리, header status에 502번이 리턴됨.

@ExceptionHandler

  • (ErrorNotFoundException.class)와 연결시킨다. ErrorNotFountException이 발동했을 때 handleNotFound method로 만든 값이 return 된다.

e

.message(e.getErrorCode().getMessage())
.status(e.getErrorCode().getStatus())
  • Error를 만들 때 전달한 e의 ErrorCode의 값을 가져온다.

controller / service

userController.java

  • 그냥 쓰던 userController에서 테스트 해봤다.

userService.java

  • 그냥 쌩 ErrorNotFoundException을 return하면 아래와 같은 긴 길이의 stackTrace와 함께 return이 된다.

실행

  • id=1 이면 controller에서 에러, id=2이면 service에서 에러가 나게 코드를 짰다.

  • @ResponseStatus(HttpStatus.BAD_GATEWAY)를 줘서 502에러가 표시되는 것을 확인할 수 있다.

참조 블로그

ControllerAdvice 참조 블로그

https://bamdule.tistory.com/92

Spring 공식문서

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

  • Global Exception임

@valid

유효성 검사

https://velog.io/@damiano1027/Spring-Valid-Validated%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%9C%A0%ED%9A%A8%EC%84%B1-%EA%B2%80%EC%A6%9D

피드백

  1. 너무 한글 블로그 문서들을 맹신하지 말 것. 공식문서나 , 영어문서, Official 문서등을 통해 확인절차를 걸쳐야 한다.

  2. 어느 정도 괜찮은 글을 발견했으면, Official이랑 비교해보고 나서 따라해보면서 익히기. 이 때 Getter Setter Constructor등은 Lombok annotation을 이용해 코드를 줄이기. 그리고 보통 블로그 글에는 여러 기능이 합쳐져서 구현될 때가 많은데, 다 따라하려고 할 필요 없고 내가 구현하고자 하는 기능만 따라해보면 된다.

profile
티스토리로 이사했습니다! https://imsfromseoul.tistory.com/ + https://camel-man-ims.tistory.com/

0개의 댓글