SpringBoot 全局异常处理 发表于 2021-04-16 | 分类于 ---SpringBoot | 其实早该整理出来的,一直没来得及弄。 pom依赖1234567891011 <!--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> 代码实现1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package 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@Slf4jpublic 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(); // } }}