全局异常统一处理
一、异常处理类
MyExceptionControllerAdvice.java
1 @Slf4j 2 @RestControllerAdvice(basePackages = "com.xxx.controller") 3 public class MyExceptionControllerAdvice { 4 5 6 /** 7 * @ExceptionHandler 是为了告诉RestControllerAdvice能处理哪些异常 8 * @param e 9 * @return 10 */ 11 @ExceptionHandler(value= MethodArgumentNotValidException.class) 12 public R handleVaildException(MethodArgumentNotValidException e){ 13 log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass()); 14 //获取数据校验的结果 15 BindingResult bindingResult = e.getBindingResult(); 16 17 Map<String,String> errorMap = new HashMap<>(); 18 /** 19 * 获取所有的错误消息 20 * key 存错误字段 21 * value 存message 22 */ 23 bindingResult.getFieldErrors().forEach((fieldError)->{ 24 errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()); 25 }); 26 return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap); 27 } 28 29 @ExceptionHandler(value = Throwable.class) 30 public R handleException(Throwable throwable){ 31 32 log.error("错误:",throwable); 33 return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg()); 34 } 35 }
关于R,是从人人开发平台Copy来的,用于封装返回数据的
1 /** 2 * 返回数据 3 * 4 * @author Mark sunlightcs@gmail.com 5 */ 6 public class R extends HashMap<String, Object> { 7 private static final long serialVersionUID = 1L; 8 9 public R() { 10 put("code", 0); 11 put("msg", "success"); 12 } 13 14 public static R error() { 15 return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员"); 16 } 17 18 public static R error(String msg) { 19 return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg); 20 } 21 22 public static R error(int code, String msg) { 23 R r = new R(); 24 r.put("code", code); 25 r.put("msg", msg); 26 return r; 27 } 28 29 public static R ok(String msg) { 30 R r = new R(); 31 r.put("msg", msg); 32 return r; 33 } 34 35 public static R ok(Map<String, Object> map) { 36 R r = new R(); 37 r.putAll(map); 38 return r; 39 } 40 41 public static R ok() { 42 return new R(); 43 } 44 45 @Override 46 public R put(String key, Object value) { 47 super.put(key, value); 48 return this; 49 } 50 public Integer getCode() { 51 52 return (Integer) this.get("code"); 53 } 54 55 }
关于BizCodeEnume,这个枚举类中定义了一些常用的错误码和错误信息
1 public enum BizCodeEnume { 2 UNKNOW_EXCEPTION(10000,"系统未知异常"), 3 VAILD_EXCEPTION(10001,"参数格式校验失败"); 4 5 private int code; 6 private String msg; 7 BizCodeEnume(int code,String msg){ 8 this.code = code; 9 this.msg = msg; 10 } 11 12 public int getCode() { 13 return code; 14 } 15 16 public String getMsg() { 17 return msg; 18 } 19 }