Spring 控制器建议异常处理程序总是返回 404
Spring Controller Advice Exception Handler always Returning 404
@ExceptionHandler return 在控制器中调用时,它是一个带有 MyResponse 对象的 200 响应,但是当从 ControllerAdvice 调用它时,它 return 是带有通用 404 消息的 404。
我希望它 return 带有 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 {
问题是我的异常处理程序需要 @ResponseBody
注释。
我的控制器在 Spring 中隐式执行此操作,但我必须在外部指定它。
旁注:我必须删除 @EnableWebMvc
注释才能使我的 junit 测试正常工作,因为我在我的测试配置中的其他地方初始化上下文(即使在服务器 运行 时一切正常)
@ExceptionHandler return 在控制器中调用时,它是一个带有 MyResponse 对象的 200 响应,但是当从 ControllerAdvice 调用它时,它 return 是带有通用 404 消息的 404。 我希望它 return 带有 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 {
问题是我的异常处理程序需要 @ResponseBody
注释。
我的控制器在 Spring 中隐式执行此操作,但我必须在外部指定它。
旁注:我必须删除 @EnableWebMvc
注释才能使我的 junit 测试正常工作,因为我在我的测试配置中的其他地方初始化上下文(即使在服务器 运行 时一切正常)