对于springboot项目来说,业务代码频繁的使用try catch是非常不友好的,而且代码不美观,因此,需要对全局异常进行统一处理。
本文将介绍如何使用@ControllerAdvice和@ExceptionHandler来对异常进行统一处理。
一.目录结构
二.目录下文件内容
2.1 pom.xml
在pom.xml文件中,只需要引入web依赖即可
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.6.2</version>
</parent>
<dependencies>
<!-- web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.2 application.yml
这里只是简单的配了下启动端口。
server:
port: 8080
2.3 GlobalExceptionHandler.class
这里将@ControllerAdvice注解标注在需要声明全局异常处理的类上面,将@ExceptionHandler注解放在异常处理方法上面,括号里的类便是需要进行处理异常的类,在这里简单的使用Excpetion.class来进行演示。
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(Exception.class)
public String onException(Exception e) {
return e.getMessage();
}
}
2.4 TestController.class
@RestController
public class TestController {
@GetMapping("/test")
public void test() {
throw new RuntimeException("出错啦!");
}
}
2.5 测试结果
使用postman来进行测试,访问http://localhost:8080/test,可见,返回“出错啦”
2.6 自定义异常返回
这里以业务异常为例,创建BusinessException.class来代表业务异常,该类需要去继承RuntimeException类,并实现其构造方法
/**
* @author anxin
* @date 2022/3/29 22:38
*/
public class BusinessException extends RuntimeException{
public BusinessException(String message) {
super(message);
}
}
修改TestController.class文件,使其抛出BusinessException
/**
* @author anxin
* @date 2022/3/28 21:57
*/
@RestController
public class TestController {
@GetMapping("/test")
public void test() {
throw new BusinessException("自定义异常!");
}
}
使用postman测试工具可以看到,返回值为“自定义异常”,可见自定义异常成功!