在学习自定义异常处理时,为了快捷测试,使用@ExceptionHandler直接捕获了Exception.class,而也没有定义异常,而是直接访问不存在的页面,导致抛出的异常为NoHandlerFoundException
。
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(Exception.class)
public Map<String, Object> handleException(Exception e){
System.out.println(1);
Map<String,Object> map = new HashMap<>();
map.put("message",e.getMessage());
map.put("ext", "错误");
return map;
}
}
但是根据DispatcherServlet源码,只有当this.throwExceptionIfNoHandlerFound
为true时才会把异常抛出来,而默认为false,所以在捕获这个异常的时候,需要在配置文件中修改这个属性。
private boolean throwExceptionIfNoHandlerFound = false;
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping for " + request.getMethod() + " " + getRequestUri(request));
}
if (this.throwExceptionIfNoHandlerFound) {
throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request), (new ServletServerHttpRequest(request)).getHeaders());
} else {
response.sendError(404);
}
}
此外,还需要关闭静态资源映射,因为出错后会按error/404,/error等路径去寻找错误页面,找不到就会按照默认建立错误页面。修改后:
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false