SpringBoot 全局异常处理

其实早该整理出来的,一直没来得及弄。

pom依赖

1
2
3
4
5
6
7
8
9
10
11
  <!--lombok-->
pom依赖 <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

代码实现

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.decathlon.easypromo.config;

import com.decathlon.easypromo.util.EPException;
import com.decathlon.easypromo.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
* 全局异常处理(仅限于 Controller 层)
*
* @author 陶攀峰
* @version 1.0
* @date 2020-10-21 10:40
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 仅处理 EPException.class 异常类型数据
*
* @author 陶攀峰
* @date 2021-01-12 11:55
*/
@ExceptionHandler(value = EPException.class)
public R handleBaseException(EPException e) {
log.error(e.getMessage(), e);
return R.error(e.getCode(), e.getMessage());
}

/**
* 除了上面的 EPException.class 异常类型,其他异常都用这个处理
*
* @author 陶攀峰
* @date 2021-01-12 11:55
*/
@ExceptionHandler(value = Exception.class)
public R handleException(Exception e) {
log.error(e.getMessage(), e);
return R.error(EPException.exceptionStackTraceToString(e));
// EPException 这个类的信息就不放出来了,把这个方法放在下面
//
// /**
// * 将异常的堆栈信息,转为字符串
// *
// * @param e 异常对象
// * @return 异常的堆栈信息,转为字符串
// * @author 陶攀峰
// * @date 2021-02-04 10:35
// */
// public static String exceptionStackTraceToString(Exception e) {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// e.printStackTrace(new PrintStream(outputStream));
// return outputStream.toString();
// }
}

}