The @ExceptionHandler returns a 200 response with a MyResponse object when called within the controller, but when it is called from ControllerAdvice it returns 404 with a generic 404 message. I want it to return a 200 response with a MyResponse object.
My code for exception handling below, both in the Controller and ControllerAdvice. I commented it out in the Controller when testing ControllerAdvice. Debugging showed the method being called in the ControllerAdvice after commenting out in the controller
@ExceptionHandler(MyException.class) public MyResponse handleMyException(HttpServletRequest req, MyException e) { return new MyResponse(MyResponse.ERROR_CODE, e.getErrorCode(), e.getMessage(), "", null); }
Below is how I define my ControllerAdvice.
@EnableWebMvc @ControllerAdvice @ResponseStatus(value= HttpStatus.OK) public class ControllerAdviceExceptionHandler {
The problem was that my exception handler needed the @ResponseBody
annotation.
My controller did this implicitly in Spring but I had to specify it externally.
Sidenote: I had to remove the @EnableWebMvc
annotation for my junit tests to work as I was initialising the context elsewhere in my test configurations (even though everything worked perfectly when the server was running)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With