参考:https://blog.csdn.net/qq_22860341/article/details/81222379
https://www.cnblogs.com/magicalSam/p/7198420.html
自定义异常处理(全局异常处理)
1、编写自定义异常类:
/** * @description:统一异常处理 * @author: Administrator * @date: 2019-03-28 11:16 */ public class MyException extends RuntimeException{ private Integer code; private String msg; public MyException(){ } public MyException(String msg){ super(msg); } public MyException(Integer code,String msg){ super(msg); this.code=code; this.msg=msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
2、编写全局异常处理类
/** * @description: controller 增强器 * @author: Administrator * @date: 2019-04-12 09:08 */ @ControllerAdvice public class MyControllerAdvice { public static Log log = LogFactory.getLog(MyControllerAdvice.class); /** * 全局异常捕捉处理 * @param ex * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Map errorHandler(Exception ex) { Map map = new HashMap(); map.put("code", 100); map.put("msg", ex.getMessage()); return map; } /** * 拦截捕捉自定义异常 MyException.class * @param ex * @return */ @ResponseBody @ExceptionHandler(value = MyException.class) public Map myErrorHandler(MyException ex) { Map map = new HashMap(); map.put("code", ex.getCode()); map.put("msg", ex.getMsg()); return map; } }
3、controller中抛出异常进行测试。
/** * @description: 异常测试 * @author: Administrator * @date: 2019-03-28 11:26 */ @RestController @RequestMapping("/ceshi") public class ExceptionController { @GetMapping("/a") public AppResult<String> findall(String aa){ if (aa==null){ throw new MyException(4002,"测试错误"); // return AppResultBuilder.success("测试错误", ResultCode.SUCCESS); } return AppResultBuilder.success("测试", ResultCode.SUCCESS); } }
4.测试: