Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controller Advice Exception Handler always Returning 404

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 {
like image 506
tt_Gantz Avatar asked Nov 28 '15 03:11

tt_Gantz


1 Answers

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)

like image 148
tt_Gantz Avatar answered Oct 16 '22 18:10

tt_Gantz