Spring Boot 404:未捕获控制器建议中的未找到处理程序异常



因此,当用户试图调用我的应用程序未知的url时,我正在尝试发送自定义答案。为此,我首先将添加到应用程序中。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]

ALso,当我在处理程序中设置断点并调试测试时,执行从未在任何断点停止。

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

点击此处查看更多信息,以100+有用性得分堆叠已接受的答案->单元测试MockHttpServlet请求未返回内容类型

相关内容

最新更新