所以当用户试图调用我的应用程序未知的网址时,我试图发送一个自定义的答案。为此,我首先添加到我的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.PageNotFind:没有映射的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:为[class org. frame.web.servlet.NoHandlerFoundException]映射的Ambiguous@ExceptionHandler方法
此外,当我在处理程序中放置断点并调试测试时,执行永远不会在任何断点停止。
因此,似乎MockMvc在使用异常处理程序时构建MockHttpServletRequest时遇到了问题,因此内容为空。当我运行我的springboot应用程序并尝试在我的导航器中调用未知的url时,它起作用了。我有预期的错误404;带有正文:使用覆盖方法未找到
处理程序。
查看更多这里,堆栈接受答案与100有用性得分-