SpringBoot全局异常处理

通用异常处理

其实Spring系列的项目全局异常处理方式早已存在,只不过我们一直忙于搬砖,很少停下脚步去审视这个日夜与我们相伴的朋友。为了贴合主题,本次主要针对SpringBoot全局异常处理进行举例说明。SpringBoot中有一个@ControllerAdvice的注解,使用该注解即表示开启全局异常捕获,接下来我们只需在自定义的方法上使用@ExceptionHandler注解,并定义捕获异常的类型,对这种类型的异常进行统一的处理。

一、

在config配置包下新建全局捕获异常处理类

二、根据具体要捕获的异常编写处理类

假如我们需要针对NullException(空指针异常,是Java程序员最痛恨的异常,没有之一)进行全局处理(如下所示)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestControllerAdvice
public class GlobalCatchException {

/**
* 空指针异常
* @param e
* @return com.zhulin.ascentweb.dto.Result
* @date 2019/9/8 9:58
*/
@ExceptionHandler(value = NullPointerException.class)
public BaseResponseFacade exceptionHandler(HttpServletRequest req, NullPointerException e){
log.error("发生空指针异常!原因是:",e);
return ResponseUtil.error(e);
}

当然,你自己也可以自定义异常处理方法

三、自定义异常

先自定义一个异常

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
26
27
28
29
30
31
32

public class ServiceException extends RuntimeException{
private Integer code;

/**
* 使用已有的错误类型
* @param type 枚举类中的错误类型
*/
public ServiceException(ErrorType type){
super(type.getContent());
this.code = type.getStatus();
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

/**
* 自定义错误类型
* @param code 自定义的错误码
* @param msg 自定义的错误提示
*/
public ServiceException(Integer code, String msg){
super(msg);
this.code = code;
}
}

然后在全局异常捕获config中:

1
2
3
4
@ExceptionHandler(ServiceException.class)
public Result handle(ServiceException se){
return ResultUtils.errorResponse(se.getCode(),se.getMessage());
}

最后在需要抛出异常的地方

1
2
3
4
5
6
@RequestMapping("/")
public void index(String title){
if(" ".equals(title)){
throw new ServiceException(ErrorType.INTERNAL_SERVER_ERROR);
}
}

最后看结果: