Spring Controller Advice Exception Handler总是返回404

时间:2015-11-28 03:46:53

标签: java spring spring-mvc exception-handling 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);
}

以下是我定义ControllerAdvice的方法。

@EnableWebMvc 
@ControllerAdvice 
@ResponseStatus(value= HttpStatus.OK)
public class ControllerAdviceExceptionHandler {

1 个答案:

答案 0 :(得分:3)

问题是我的异常处理程序需要@ResponseBody注释。 我的控制器在Spring中隐式执行了这个操作,但是我必须在外部指定它。

旁注:我必须删除我的junit测试的@EnableWebMvc注释才能工作,因为我在测试配置的其他地方初始化上下文(即使服务器运行时一切都运行良好)

相关问题