【问题标题】:Spring Controller Advice Exception Handler always Returning 404Spring Controller Advice Exception Handler 总是返回 404
【发布时间】:2016-03-02 05:58:51
【问题描述】:

@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 {

【问题讨论】:

    标签: java spring spring-mvc exception-handling http-status-code-404


    【解决方案1】:

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

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

    【讨论】:

    • 如果我需要在异常处理程序中返回页面怎么办?
    猜你喜欢
    • 2020-02-09
    • 2019-03-20
    • 2020-02-03
    • 1970-01-01
    • 2016-11-19
    • 2018-07-15
    • 1970-01-01
    • 2021-02-07
    • 2021-08-05
    相关资源
    最近更新 更多