Spring Controller Advice Exception Handler 总是返回 404

tt_*_*ntz 4 java spring exception-handling spring-mvc http-status-code-404

@ExceptionHandler 在控制器中调用时返回一个带有 MyResponse 对象的 200 响应,但是当它从 ControllerAdvice 调用时它返回 404 和一个通用的 404 消息。我希望它返回一个带有 MyResponse 对象的 200 响应。

我的异常处理代码如下,在 Controller 和 ControllerAdvice 中。我在测试 ControllerAdvice 时在 Controller 中注释掉了它。调试显示在控制器中注释掉后在 ControllerAdvice 中调用的方法

@ExceptionHandler(MyException.class)
     public MyResponse handleMyException(HttpServletRequest req, MyException e) {
    return new MyResponse(MyResponse.ERROR_CODE, e.getErrorCode(), e.getMessage(), "", null);
}
Run Code Online (Sandbox Code Playgroud)

下面是我如何定义我的 ControllerAdvice。

@EnableWebMvc 
@ControllerAdvice 
@ResponseStatus(value= HttpStatus.OK)
public class ControllerAdviceExceptionHandler {
Run Code Online (Sandbox Code Playgroud)

tt_*_*ntz 7

问题是我的异常处理程序需要@ResponseBody注释。我的控制器在 Spring 中隐式地做到了这一点,但我必须在外部指定它。

旁注:@EnableWebMvc当我在测试配置的其他地方初始化上下文时,我必须删除我的 junit 测试的注释(即使服务器运行时一切正常)