본문 바로가기

Back-end/Spring

[Spring] ControllerAdvice

@Controller 나 @RestController 에서 발생한 예외를 한 곳에서 관리하고 처리할 수 있게 도와주는 어노테이션

 

즉, 스프링에서 예외 처리를 전역적으로 핸들링하기 위해 @ControllerAdvice 어노테이션 사용함

 

 

@RestControllerAdvice
public class =RestControllerAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    MessageSource messageSource;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // TODO Auto-generated method stub
        return true;
        //return false;
    } // method

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // TODO Auto-generated method stub

        // Webpage Not found
        // body가 String이고, Cotent-type이 text/html이고, request uri에 api가 포함이 안되어 있으면 webpage 호출이라고 판단
        // error 페이지를 로드하여, body로 전달

        boolean notCodeReviewResource = false;
        if (request.getURI().getPath().contains("swagger") || request.getURI().getPath().contains("v3/api-docs") || request.getURI().getPath().contains("actuator")) {
            notCodeReviewResource = true;
        }


        if (body instanceof Resource || body instanceof byte[] || body instanceof ResourceRegion || body instanceof CodeReviewRestMessage || notCodeReviewResource || body instanceof CodeReviewRestErrorMessage) {
            return body;
        } else {
            if (request.getURI().getPath().contains("inout") || request.getURI().getPath().contains("proxy")) {
                return CodeReviewRestMessage.builder().messageSource(messageSource).returnCode("CR00001").data(body).build();
            } else {
                return body != null ? CodeReviewRestMessage.builder().messageSource(messageSource).returnCode("CR00002").data(body).build() : CodeReviewRestMessage.builder().messageSource(messageSource).returnCode("CR00001").build();
            } // if
        } // if
    } // method

    public String exceptionToString(Exception e) {
        StringWriter error = new StringWriter();
        e.printStackTrace(new PrintWriter(error));
        return error.toString();
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleOtherExceptions(Exception exception, WebRequest request) {
        RestMessage RestMessage = null;
        if (exception instanceof AuthenticationException) {
        
        .
        .
        .
        // 이런식으로 예외 처리
        
            RestMessage = RestMessage.builder().returnCode("CRB5002").messageSource(messageSource).build();
        } else if (exception instanceof MethodArgumentNotValidException) {
            RestMessage = RestMessage.builder().returnCode("CRB0001").messageSource(messageSource).build();
        } else {
            RestMessage = RestMessage.builder().returnCode("CRS0003").messageSource(messageSource).build();
        } // if

        return ResponseEntity.status(HttpStatus.OK).body(RestMessage);
    }
}