SpringBoot. ResponseBodyAdvcie after ExcpeitonHandler

90 views Asked by At

I got 2 @ControllerAdvice interceptors

1 - adivce for wrap response body to default response wrapper object

@ControllerAdvice
class BodyWrapper implements ResponseBodyAdvice<Object> {
       
       @Override
       public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response) {
                 return new DataResponse(body);
            }
}

2 - exception handler

@ControllerAdvice
@Slf4j
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {MyCustomException.class})
    protected ResponseEntity<?> handleCustomExceptions(
            MyCustomException ex) {
        return ResponseEntity.status(
                        ex.getMsg().getStatus().getCode())
                .body(ex.getReason().getPayload());
    }
}

Problem:

ResponseBodyAdvice catches any exceptions and then the ExceptionHandler is not called. How to prevent invoking ResponseBodyAdvice if any exception occurs? Please help!

1

There are 1 answers

1
4EACH On

In case you want to order the interceptors you can do it with @Order annotation

@ControllerAdvice
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {MyCustomException.class})
    protected ResponseEntity<?> handleCustomExceptions(
            MyCustomException ex) {
        return ResponseEntity.status(
                        ex.getMsg().getStatus().getCode())
                .body(ex.getReason().getPayload());
    }
}

In this sample I have added the constant to highest order but you can use numeric order.