Springboot 项目处理全局异常
1. 在配置文件中增加 spring.mvc.throw-exception-if-no-handler-found=true #找不到对应资源抛出异常
2. 新建异常类
@ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 系统异常处理,比如:404,500 * @param req * @param * @param e * @return * @throws Exception */ @ExceptionHandler(value = Exception.class) @ResponseBody public JSONObject defaultErrorHandler(HttpServletRequest req, Exception e){ logger.error("接口调佣出现错误 {}", e); String requestURI = req.getRequestURI(); String agent = req.getHeader("user-agent"); String ip = req.getHeader("X-Forwarded-For"); String method = req.getMethod(); Map<String, String[]> parameterMap = req.getParameterMap(); logger.error("异常请求方式为 {} {} 错误信息 {} 请求IP {} 或者 {} 请求参数 {}",method, agent, requestURI + "?" + req.getQueryString(),req.getRemoteAddr(),ip,JSON.toJSONString(parameterMap)); JSONObject json = new JSONObject(); json.put(CommonConst.DEFAULT_RESULT_CODE_KEY,ErrorCode.FAILED.getName()); if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) { json.put(CommonConst.DEFAULT_MSG_POP_KEY,ErrorCode.Not_Find_Resources); json.put(CommonConst.DEFAULT_RESULT_STATUS_KEY,ErrorCode.Not_Find_Resources.getName()); } else { json.put(CommonConst.DEFAULT_MSG_POP_KEY,ErrorCode.INTERNAL_ERROR); json.put(CommonConst.DEFAULT_RESULT_STATUS_KEY,ErrorCode.INTERNAL_ERROR.getName()); } return json; } }
3. 将该类加入springboot启动bean扫描中
结果如下:
{
"code": 0,
"message": "资源不存在",
"status": 404
}