ControllerAdvice

HandlerExceptionResolver

HTTP Problem

ResponseBodyAdvice

  • ResponseBodyAdvice
  • 반환된 body 의 데이터들을 선택된 converter 를 이용하여 json 으로 serialize 하기 전에 호출된다.
@RestControllerAdvice
public class CommonResponseAdvice implements ResponseBodyAdvice {

    /**
     * Whether this component supports the given controller method return type
     * and the selected {@code HttpMessageConverter} type.
     * @param returnType the return type
     * @param converterType the selected converter type
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * Invoked after an {@code HttpMessageConverter} is selected and just before
     * its write method is invoked.
     * @param body the body to be written
     * @param returnType the return type of the controller method
     * @param selectedContentType the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request the current request
     * @param response the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Override
    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // ExceptionHandlerAdvice 또는 Controller 에서 ResponseEntity or CommonResponse 를 리턴하는 경우 별도 작업 없이 처리
        if (body instanceof ResponseEntity || body instanceof CommonResponse) {
            return body;
        }
        
        // 그 외에는 작업할 내용 작성...
        
        return body;
    }
}