异常的分类

Exception分为运行时异常和非运行时异常

运行时异常:编译时不会报错,会在运行中报错,若空指针异常

非运行时异常:在编译时报错,如 IOException

全局异常抓取抛出
  • 自定义类设置校验规则
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//继承运行时异常类
public class ThrowException extends RuntimeException {

//此类要继承运行时异常

public ThrowException() {
super();
}

public ThrowException(String message) {
super(message);
}

public ThrowException(String message, Throwable cause) {
super(message, cause);
}

public ThrowException(Throwable cause) {
super(cause);
}

protected ThrowException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
  • 设置handler抓取异常并返回
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

//注明异常类
@ExceptionHandler(value = ThrowException.class)
@ResponseBody
public ReturnDto ErrorHandler(ThrowException e) {
log.error(e.getMessage(), e);
//将抓取的异常返回
return new ReturnDto(e.getMessage(), "406", null);
}
}
  • 使用方式
1
throw new ThrowException("此处主动抛出异常");