首先创建一个统一异常处理类
/** * 统一异常处理的类 */ @ControllerAdvice public class GlobalExceptionHandler {}
之后分别加入
当出现特定异常的时候则会被特定异常所捕获
//全局异常 @ExceptionHandler(Exception.class) @ResponseBody public R error(Exception e){ e.printStackTrace(); return R.error().message("出现了异常"); }
//特定异常 @ExceptionHandler(ArithmeticException.class) @ResponseBody public R error(ArithmeticException e){ e.printStackTrace(); return R.error().message("出现了特定异常 被除数不能为0"); }
配置自定义异常同时也要配置自定义异常处理类
模拟异常,抛出自定义异常