Spring Boot 统一异常处理
概述
在开发过程中,我们经常会遇到各种异常情况。为了提高系统的可维护性和用户体验,我们需要在系统中实现统一的异常处理方式。Spring Boot 提供了简单而强大的机制来实现全局的异常处理。本文将指导你如何使用 Spring Boot 实现统一异常处理。
步骤
步骤一:添加依赖
首先,我们需要在项目的 pom.xml 文件中添加 Spring Boot 的依赖,以及其他相关的依赖。在本例中,我们使用 Spring Boot 2.5.2 版本。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
步骤二:创建异常类
接下来,我们需要创建一个自定义的异常类,用于表示我们系统中可能发生的异常。通常,我们会创建一个继承自 RuntimeException 的异常类,例如 CustomException
。
public class CustomException extends RuntimeException {
private String message;
public CustomException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
步骤三:创建全局异常处理器
然后,我们需要创建一个全局异常处理器,用于处理系统中抛出的异常。我们可以使用 @ControllerAdvice
注解来标识这个类,并使用 @ExceptionHandler
注解来指定处理的异常类型。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
}
}
在上面的代码中,handleCustomException
方法用于处理 CustomException
类型的异常,返回一个指定状态码和消息体的响应。handleException
方法用于处理其他类型的异常,返回一个默认的错误消息。
步骤四:配置全局异常处理器
最后,我们需要将全局异常处理器配置到 Spring Boot 应用程序中。可以通过创建一个配置类,并使用 @EnableWebMvc
注解来启用全局异常处理器。
@Configuration
@EnableWebMvc
public class GlobalExceptionHandlerConfig implements WebMvcConfigurer {
@Autowired
private GlobalExceptionHandler globalExceptionHandler;
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.add(globalExceptionHandler);
}
}
在上面的代码中,我们通过 configureHandlerExceptionResolvers
方法将全局异常处理器添加到处理器解析器列表中。
效果图
下图展示了整个处理流程的时序图:
sequenceDiagram
participant Client
participant Controller
participant GlobalExceptionHandler
participant CustomException
Client->>Controller: 发送请求
Controller->>CustomException: 抛出异常
CustomException->>GlobalExceptionHandler: 异常传递
GlobalExceptionHandler-->>Client: 返回异常响应
结论
通过以上步骤,我们成功地实现了 Spring Boot 的统一异常处理。在开发过程中,我们只需要抛出自定义的异常,全局异常处理器会自动捕获并返回相应的错误消息。这样可以减少重复的代码,提高系统的可维护性和用户体验。
希望本文对你有帮助!如果你有任何疑问,请随时提问。