走进SpringBoot之统一异常处理
在我们项目中,运行时异常是非常容易出现的,前端页面进行请求如果发生异常会把异常的信息直接显示在前端页面上,这可能会导致一些敏感信息泄露,而且默认的异常信息一般也不好看,对我们排查问题也不是很方便,所以在项目中使用 统一的异常处理是非常有必要的。话不多说,直接上代码。
1.创建一个springboot的项目
pom文件中添加依赖
<!--lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.编写一个controller
package com.ccl.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExceptionController {
@RequestMapping("/testexception")
public String testexception() {
// 模拟出现异常情况
int i = 1/0;
return "testexception";
}
}
启动项目 访问 :http://127.0.0.1:8080/testexception 会出现:
这个是默认情况下的一个异常出现的情况。接下来我们进行异常统一处理
3.编写一个异常类
package com.ccl.demo.exception;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class CommonException {
/**
* 异常代码
*/
private String exceptionCode;
/**
* 异常信息
*/
private String exceptionMsg;
public CommonException() {
}
public CommonException(String exceptionCode, String exceptionMsg) {
this.exceptionCode = exceptionCode;
this.exceptionMsg = exceptionMsg;
}
@Override
public String toString() {
return "CommonException [exceptionCode=" + exceptionCode + ", "
+ "exceptionMsg=" + exceptionMsg + "]";
}
}
4.异常处理类
package com.ccl.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
@ControllerAdvice
@Slf4j
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public class CommonExceptionHandler {
//处理ArithmeticException 异常
@ExceptionHandler(ArithmeticException.class)
public String handleArithmeticException(ArithmeticException ex) {
log.info("异常信息", ex);
CommonException commonException = new CommonException();
commonException.setExceptionCode("001");
commonException.setExceptionMsg("除数不能为0"+ex.getMessage());
return commonException.toString();
}
}
上面我们对除以0发生的ArithmeticException异常进行统一处理
重启项目,访问http://127.0.0.1:8080/testexception 页面效果:
前端页面就会显示我们自定义的异常信息,这样便于我们排错和控制异常信息的输出。
基本上统一异常处理就完成了,这边写的有些简便,一般情况下在异常处理类中的
commonException.setExceptionCode("001");
commonException.setExceptionMsg("除数不能为0"+ex.getMessage());
这两句要使用枚举类进行管理,各个模块约定好各自的异常编码和异常信息这样对我们排查问题会方便许多