【问题标题】:Spring Boot 404 : no handler found exception in Controller Advice isn't catchedSpring Boot 404:未捕获控制器建议中未发现异常的处理程序
【发布时间】:2022-01-26 10:24:02
【问题描述】:

因此,当用户尝试调用我的应用程序未知的 url 时,我尝试发送自定义答案。为此,我首先将其添加到我的 application.properties(在主文件夹和测试文件夹中)

spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false

因此,如果没有找到处理程序,则会引发异常。此异常的类型应为 NoHandlerFoundException

然后我在我的控制器建议中添加了一个自定义异常处理程序 我的控制器建议(简化)

@EnableWebMvc // (I tried with and without it doesn't change the error)
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) // (I tried with and without it doesn't change the error)
public class ExceptionsHandler extends ResponseEntityExceptionHandler {
    // invalid route handler
    @Override
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    protected ResponseEntity<Object> handleNoHandlerFoundException(
    NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();

        ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getLocalizedMessage(), error);
        return new ResponseEntity<>(apiError.getErrors(), new HttpHeaders(), apiError.getStatus());
    }
}

使用这个,在我的测试中调用一个未知的 url 时使用:

this.mvc.perform(get("/ttt"))
        .andDo(print())
        .andExpect(status().isNotFound())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.error").value("No Handler found for GET /ttt"));

我进入调试控制台: o.s.web.servlet.PageNotFound : No mapping for GET /ttt 虽然,答案没有我的自定义错误消息,因为我也在调试控制台中得到:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

然后我尝试了

    @ExceptionHandler({NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseEntity<Object> handleNoHandler(HttpServletRequest request, Exception ex) {
        String error = ex.getMessage();
        return new ResponseEntity<>(error, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }

但是随后会抛出 非法状态异常:无法加载应用程序上下文

IllegalStateException:Ambiguous @ExceptionHandler method mapped for [class org.framework.web.servlet.NoHandlerFoundException]

另外,当我在我的处理程序中设置断点并调试我的测试时,执行永远不会在任何断点处停止。

【问题讨论】:

  • 我也尝试在我的 application.properties 中使用 spring.mvc.static-path-pattern= /** spring.web.resources.add-mappings=false server.error.whitelabel.enabled=假`

标签: java spring spring-boot spring-mvc controller-advice


【解决方案1】:

因此,在使用异常处理程序时,MockMvc 似乎在构建 MockHttpServletRequest 时遇到了问题,因此内容为空。 当我运行我的 springboot 应用程序并尝试在我的导航器中调用一个未知的 url 时,它可以工作。我使用 覆盖方法 获得了预期的 error 404; with body : No handler found

在此处查看更多信息,将接受的答案与 100+ 有用性得分叠加 -> Unit test MockHttpServletRequest not returning content type

【讨论】:

  • 我停止使用 MockMvc 来使用 org.springframework.boot.test.web.client.TestRestTemplate;它对我很有效。我能够测试我所有的案例
猜你喜欢
  • 2016-10-14
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
相关资源
最近更新 更多