1 特定异常处理

针对不同的异常类型,我们希望有不同的处理,下面实现特定异常的处理。

// 特定异常处理
@ExceptionHandler(ArithmeticException.class)
@ResponseBody //返回数据
public R error(ArithmeticException e){
    e.printStackTrace();
    return R.error().message("执行ArithmeticException异常处理...");
}

测试结果如下。

alt 发现response body中的message只包括特定的异常,不包括全局异常。这是因为:异常处理机制是,先查找对应异常的特定处理,如有则进行特定异常处理,否则进行全局异常处理。

2 自定义异常处理

(1)创建自定义异常类

在exceptionhandler包下新建GuliException类。

@Data // lombok注解:生成getter、setter
@NoArgsConstructor // lombok注解:生成无参构造器
@AllArgsConstructor // lombok注解:生成带参构造器
public class GuliException extends RuntimeException{
    int code;
    String msg;
}

(2)自定义异常处理

// 自定义异常处理
@ExceptionHandler(GuliException.class)
@ResponseBody //返回数据
public R error(GuliException e){
    e.printStackTrace();
    return R.error().code(e.getCode()).message(e.getMsg());
}

(3)抛出异常

@ApiOperation("查找教师")
@GetMapping("/findTeacher/{id}")
public R findTeacher(@PathVariable String id) {
    try {
        int i = 1 / 0;
    } catch (Exception e) {
        throw new GuliException(1234, "自定义异常");
    }
    EduTeacher eduTeacher = eduTeacherService.getById(id);
    return R.ok().data("item", eduTeacher);
}