Open TemplarJQ opened 5 years ago
前端访问不到的页面根本没有进入任何一个Controller,也就无法引起异常,因此也就没有办法引起BaseController对于异常的处理过程,因此需要改进。
加入GobalController的控制:
@ControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler(Exception.class)
@ResponseBody
public CommonReturnType doError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception ex) {
ex.printStackTrace();
Map<String,Object> responseData = new HashMap<>();
if( ex instanceof BusinessException){
BusinessException businessException = (BusinessException)ex;
responseData.put("errCode",businessException.getErrCode());
responseData.put("errMsg",businessException.getErrMsg());
}else if(ex instanceof ServletRequestBindingException){
responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR.getErrCode());
responseData.put("errMsg","url绑定路由问题");
}else if(ex instanceof NoHandlerFoundException){
responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR.getErrCode());
responseData.put("errMsg","没有找到对应的访问路径");
}else{
responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
responseData.put("errMsg",EmBusinessError.UNKNOWN_ERROR.getErrMsg());
}
return CommonReturnType.create(responseData,"fail");
}
}
一个正常的请求为:
http://localhost:8090/user/get?id=1
前面过程中我们的GlobalExceptionHandler处理了没有参数的情况
http://localhost:8090/user/get
当我们在url中故意修改错时,是无法处理的
http://localhost:8090/user/get1
在application.properties中修改并添加
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
404异常问题的处理
现在的网站对于,比如说前端页面上:
改为
引起的404问题,实际上是无法得到解决的。