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!
In case you want to order the interceptors you can do it with
@Order
annotationIn this sample I have added the constant to highest order but you can use numeric order.