自定义异常
自定义异常要继承RuntimeException
public class ShowtimeException extends RuntimeException {
private Integer code;
public ShowtimeException(ResultEnum resultEnum){
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
异常处理类
用@ControllerAdvice申明的类可以在Spring扫描时自动扫描,在异常的处理中@ControllerAdvice会优先选择用@ExceptionHandler标注的方法来做异常的处理。
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
// 判断异常是自定义异常
if (e instanceof ShowtimeException){
ShowtimeException showtimeException = (ShowtimeException) e;
return ResultUtil.fail(showtimeException.getCode(), showtimeException.getMessage());
} else {
return ResultUtil.fail(-1, "e.getMessage()");
}
}
}
这样当我们在代码中抛出自定义异常时,就可以被捕获,返回统一格式的结果
Controller中的代码为:
@GetMapping("/showtime/getAge/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception {
showtimeService.getAge(id);
}
Service中的代码为:
@Service
public class ShowtimeService {
@Autowired
private ShowtimeRepository showtimeRepository;
public void getAge(Integer id) throws Exception {
Showtime showtime = showtimeRepository.getOne(id);
Integer age = showtime.getAge();
if (age < 10){
throw new ShowtimeException(ResultEnum.ERROR_ONE);
} if (age > 12 && age < 18){
throw new ShowtimeException(ResultEnum.ERROR_TWO);
}
}
}
通过postman发送请求,http://localhost:9080/showtime/getAge/2 ,返回结果:
{
"msg": "年龄大于12小于18",
"code": 1,
"data": null
}
参考慕课网地址: Aop之统一异常处理 http://www.imooc.com/learn/810