欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > Spring Boot 实现全局异常处理

Spring Boot 实现全局异常处理

2024/10/24 17:24:08 来源:https://blog.csdn.net/weixin_41203765/article/details/141423727  浏览:    关键词:Spring Boot 实现全局异常处理

在Spring Boot中,实现全局异常处理是一个常见的需求,它可以帮助我们集中处理应用中可能抛出的异常,并返回统一的响应格式给前端。这不仅可以减少代码重复,还能提高应用的可维护性和用户体验。

下面是一个简单的Spring Boot全局异常处理的实现步骤:

1. 创建自定义异常类(可选)

首先,你可以根据需要创建一些自定义异常类,以便在业务逻辑中抛出这些具体的异常。这样做的好处是可以让异常更加语义化,方便后续的处理和日志记录。

public class CustomException extends RuntimeException {  private static final long serialVersionUID = 1L;  private String errorCode;  public CustomException(String message, String errorCode) {  super(message);  this.errorCode = errorCode;  }  // Getter 和 Setter  public String getErrorCode() {  return errorCode;  }  public void setErrorCode(String errorCode) {  this.errorCode = errorCode;  }  
}

2. 创建全局异常处理器

接下来,创建一个全局异常处理器,通过@ControllerAdvice@RestControllerAdvice(如果你使用的是RESTful服务)注解来标注这个类,然后使用@ExceptionHandler注解来指定它要处理的异常类型。

@RestControllerAdvice  
public class GlobalExceptionHandler {  @ExceptionHandler(value = Exception.class)  public ResponseEntity<Object> handleAllExceptions(Exception e) {  // 这里可以根据具体的异常类型进行更细致的处理  // 例如,如果捕获到CustomException,则可以返回更具体的错误码和信息  // 简单的示例:返回状态码500和异常信息  ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Internal Server Error");  return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);  }  @ExceptionHandler(value = CustomException.class)  public ResponseEntity<Object> handleCustomException(CustomException e) {  ApiError apiError = new ApiError(e.getErrorCode(), e.getMessage());  return new ResponseEntity<>(apiError, HttpStatus.valueOf(e.getErrorCode().startsWith("4") ? Integer.parseInt(e.getErrorCode().substring(0, 3)) : HttpStatus.INTERNAL_SERVER_ERROR.value()));  }  // ApiError 是一个简单的POJO类,用于封装错误信息  private static class ApiError {  private int status;  private String message;  public ApiError(int status, String message) {  this.status = status;  this.message = message;  }  // Getter 和 Setter  }  
}

注意:ApiError是一个简单的POJO类,用于封装错误信息,你可以根据实际需求调整它的结构。

3. 测试全局异常处理

现在,你可以在应用的任何地方抛出异常,并查看全局异常处理器是否正确地捕获并处理了这些异常。

4. 注意事项

  • 确保你的全局异常处理器类被Spring Boot扫描到,通常这意味着它应该位于Spring Boot的主类或启动类所在的包或子包中。
  • 根据你的应用需求,你可能需要为不同类型的异常编写多个@ExceptionHandler方法。
  • 考虑将异常信息记录到日志中,以便在问题发生时进行追踪和调试。
  • 如果你的应用是RESTful服务,并且你希望为前端返回统一的响应格式,那么使用@RestControllerAdviceResponseEntity是一个很好的选择。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com