目录
前言:
因为纯后端项目,需求中有需要对URI没有的情况,进行错误码返回。
所以加上了这个页面404的异常捕获~
不得不说,springboot 是真的方便
至于全局异常处理,之前有写过:
https://blog.youkuaiyun.com/pmdream/article/details/95969267
1. springboot做了默认的URI找不到的处理
{
"timestamp": 1570505276787,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/detect/xxx"
}
2. 可以在yml配置文件中加入下面内容
#出现错误时, 直接抛出异常(便于异常统一处理,否则捕获不到404) mvc: throw-exception-if-no-handler-found: true #不要为工程中的资源文件建立映射 resources: add-mappings: false
3. 统一异常捕获
@ExceptionHandler(value = {NoHandlerFoundException.class})
@ResponseBody
public Result noHandlerFoundException(HttpServletRequest req, Exception e) {
Result result = new Result(RespCode.ERROR_6_.getCode(), RespCode.ERROR_6_.getMsg(), null);
errorLog(req, e , result);
return result;
}
就是捕获到这个NoHandlerFoundException 就可以抛出URI没有的错误码~