只需要将自定义的异常类继承至RuntimeException即可。
示例代码:
/**
* GirlException包含两个字段: code 和 message (message继承至RuntimeException)
*/
public class GirlException extends RuntimeException {
private Integer code;
public GirlException(Integer code, String message){
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code){
this.code = code;
}
}
// 在Service中使用自定义Exception
@Service
public class GirlService {
@Autowired
private GirlRepository girlRepository;
public void getAge(Integer id) {
Girl girl = girlRepository.findById(id).get();
Integer age = girl.getAge();
if (age <= 10) {
throw new GirlException(100, "你还在上小学吧");
}
if (age < 16) {
throw new GirlException(101, "你可能在上中学");
}
}
}
// 自定义ControllerAdvice
@ControllerAdvice
public class ExceptionHandle {
/**
* 捕获GirlException异常
* 启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在被 @RequestMapping 注解的方法上。
* @param ge
* @return
*/
@ExceptionHandler(value = GirlException.class)
@ResponseBody
public Result girlHandle(GirlException ge) {
return ResultUtil.error(ge.getCode(), ge.getMessage());
}
/**
* 捕获全局异常
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
return ResultUtil.error(-1, "未知错误");
}
}