搭建单体SpringBoot项目 统一异常处理

所有的异常信息进行统一处理。

关于异常相关的知识,请移步到Java基础 - 异常

结果展示

加入测试代码:

image-20221013103954677 image-20221013104123788

请求响应信息:

image-20221013104312090 image-20221013104335886 image-20221013104357673

添加统一异常处理类

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
import com.panda.base.exception.custom.PandaException;
import com.panda.base.result.vo.ApiResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class PandaGlobalExceptionHandler {

/**
* 这是我的自定义异常
*
* @param e
* @return
*/
@ExceptionHandler({PandaException.class})
public ApiResult runtimeException(PandaException e) {
return ApiResult.fail("PandaException:" + e);
}

/**
* 兜底异常,其他异常都没有匹配到的会来到这个方法进行处理。
*/
@ExceptionHandler({Exception.class})
public ApiResult Exception(Exception e) {
return ApiResult.fail("Exception:" + e);
}

}