首页
点滴
SpringBoot 全局统一异常处理
#### 1、新建一个统一的操作消息返回类AjaxResult ``` /** * 操作消息提醒 * @author Frank * */ public class AjaxResult extends HashMap
{ private static final long serialVersionUID = 1L; /** * 初始化一个新创建的 Message 对象 */ public AjaxResult() {} /** * 返回错误消息 * * @return 错误消息 */ public static AjaxResult error() { return error(1, "操作失败"); } /** * 返回错误消息 * * @param msg 内容 * @return 错误消息 */ public static AjaxResult error(String msg) { return error(500, msg); } /** * 返回错误消息 * * @param code 错误码 * @param msg 内容 * @return 错误消息 */ public static AjaxResult error(int code, String msg) { AjaxResult json = new AjaxResult(); json.put("code", code); json.put("msg", msg); return json; } /** * 返回成功消息 * * @param msg 内容 * @return 成功消息 */ public static AjaxResult success(String msg) { AjaxResult json = new AjaxResult(); json.put("msg", msg); json.put("code", 0); return json; } /** * 返回成功消息 * @param obj 对象 * @return */ public static AjaxResult success(Object obj) { AjaxResult json = new AjaxResult(); json.put("msg", "操作成功"); json.put("data", obj); json.put("code", 0); return json; } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } /** * 返回成功消息 * * @param key 键值 * @param value 内容 * @return 成功消息 */ @Override public AjaxResult put(String key, Object value) { super.put(key, value); return this; } } ``` #### 2、新建一个业务异常消息类 ``` /** * 业务异常 * @author Frank * */ public class BusinessException extends RuntimeException { private static final long serialVersionUID = 1L; protected final String message; public BusinessException(String message){ this.message = message; } @Override public String getMessage() { return message; } } ``` #### 3、新建全局统一异常默认处理类,并用注解 @RestControllerAdvice 修饰 ``` /** * 自定义异常处理器 * @author Frank * */ @RestControllerAdvice public class DefaultExceptionHandler{ private static final Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class); /** * 请求方式不支持 */ @ExceptionHandler({ HttpRequestMethodNotSupportedException.class }) public AjaxResult handleException(HttpRequestMethodNotSupportedException e){ log.error(e.getMessage(), e); return AjaxResult.error("不支持' " + e.getMethod() + "'请求"); } /** * 拦截未知的运行时异常 */ @ExceptionHandler(RuntimeException.class) public Object runtimeException(RuntimeException e,HttpServletRequest req){ log.error("运行时异常:", e); // 使用HttpServletRequest中的header检测请求是否为ajax, 如果是ajax则返回json, 如果为非ajax则返回view(即ModelAndView) String contentTypeHeader = req.getHeader("Content-Type"); String acceptHeader = req.getHeader("Accept"); String xRequestedWith = req.getHeader("X-Requested-With"); if ((contentTypeHeader != null && contentTypeHeader.contains("application/json")) || (acceptHeader != null && acceptHeader.contains("application/json")) || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) { return AjaxResult.error("运行时异常:" + e.getMessage()); } else { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("msg", e.getMessage()); modelAndView.addObject("url", req.getRequestURL()); modelAndView.addObject("stackTrace", e.getStackTrace()); modelAndView.setViewName("error/error"); return modelAndView; } } /** * 系统异常 */ @ExceptionHandler(Exception.class) public AjaxResult handleException(Exception e){ log.error(e.getMessage(), e); return AjaxResult.error("服务器错误,请联系管理员"); } /** * 参数绑定异常 * @param e * @return */ @ExceptionHandler(BindException.class) public AjaxResult bindException(BindException e){ log.error("参数绑定异常", e); BindingResult result = e.getBindingResult(); List
fieldErrors = result.getFieldErrors(); List
list = new ArrayList<>(); for (FieldError fieldError : fieldErrors) { String field = fieldError.getField(); String defaultMessage = fieldError.getDefaultMessage(); list.add(field+":"+defaultMessage); } return AjaxResult.error(list.toString()); } /** * 缺少请求参数异常 * @param e * @return */ @ExceptionHandler(MissingServletRequestParameterException.class) public AjaxResult missingServletRequestParameterException(MissingServletRequestParameterException e){ log.error("缺少请求参数", e); return AjaxResult.error("缺少请求参数:"+e.getParameterName()); } /** * 文件上传异常 * @param e * @return */ @ExceptionHandler(MultipartException.class) public Map
multipartException(MultipartException e){ log.error("文件上传异常", e); Map
map = new HashMap
(16); map.put("success", 0); map.put("message", "图片上传失败" + "\n支持图片格式:jpg, jpeg, gif, png, bmp, webp" + "\n文件大小限制:1MB"); return map; } /** * 入参校验异常,需要在目标Controller类上加注解:@Validated * @param * @return */ @ExceptionHandler(ConstraintViolationException.class) public AjaxResult constraintViolationException(ConstraintViolationException e){ log.error("入参校验异常",e); Set
> violations = e.getConstraintViolations(); List
list = new ArrayList<>(); for (ConstraintViolation> constraintViolation : violations) { list.add(constraintViolation.getMessage()); } return AjaxResult.error(list.toString()); } /** * 业务异常 */ @ExceptionHandler(BusinessException.class) public AjaxResult businessException(BusinessException e){ log.error(e.getMessage(), e); return AjaxResult.error(e.getMessage()); } } ```
博客分类
源码解析 (1)
Java (9)
Linux (7)
多线程 (5)
Docker (9)
SpringBoot (14)
微服务 (1)
Redis (15)
MySQL (7)
VMware (3)
Nginx (15)
MyBatis (2)
Git (7)
RabbitMQ (1)
工具类 (12)
友情链接
layui
© 2020-2021 www.chenhuazhan.com All Rights Reserved 备案号:
桂ICP备17004487号-1