全局异常处理
创建异常类,编写测试方法
@ControllerAdvice
public class GlobalExceptionHandler {
@ApiOperation("全局异常处理") // 这样写会被挨打吗?
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e) {
e.printStackTrace();
return Result.fail(null).message("执行了全局处理异常");
}
}
编写测试controller
@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@GetMapping("findAll")
public Result findAllTeacher() {
List<Teacher> list = teacherService.list();
int a = 10 / 0;
return Result.ok(list).message("查询成功").code(200);
}
}
特定异常处理
创建异常类,编写测试方法
@ControllerAdvice
public class GlobalExceptionHandler {
@ApiOperation("特定异常处理") // 这样写会被挨打吗?
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Result error(ArithmeticException e) {
e.printStackTrace();
return Result.fail(null).message("除数不能为0");
}
}
编写测试controller
@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@GetMapping("findAll")
public Result findAllTeacher() {
List<Teacher> list = teacherService.list();
int a = 10 / 0;
return Result.ok(list).message("查询成功").code(200);
}
}
自定义异常处理
创建自定义异常类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GgktException extends RuntimeException {
private Integer code;
private String msg;
}
编写自定义异常处理代码
@ControllerAdvice
public class GlobalExceptionHandler {
@ApiOperation("自定义异常处理") // 这样写会被挨打吗?
@ExceptionHandler(GgktException.class)
@ResponseBody
public Result error(GgktException e){
e.printStackTrace();
return Result.fail(null).message(e.getMsg()).code(e.getCode());
}
}
编写测试controller
@RestController
@RequestMapping(value = "/admin/vod/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@GetMapping("findAll")
public Result findAllTeacher() {
List<Teacher> list = teacherService.list();
int a = 10 / 0;
return Result.ok(list).message("查询成功").code(200);
}
}