You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SweetAlert2网络中断时确认弹窗的错误处理及加载状态实现

SweetAlert2 网络中断时的错误处理与加载状态实现

问题分析

当前代码直接执行异步下载操作,但未处理网络异常,也没有在下载过程中显示加载状态,导致用户无法感知操作进度,网络中断时也没有对应错误提示。

解决方案

通过async/await统一处理异步流程,结合SweetAlert2的加载状态和错误捕获机制,实现网络异常处理:

const handleDownload = async () => {
  setAnchorEl(null);
  const confirmResult = await Swal.fire({
    title: 'Do you want to download?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
  });

  if (confirmResult.isConfirmed) {
    // 显示下载加载弹窗
    const loadingPopup = Swal.fire({
      title: 'Downloading...',
      icon: 'info',
      allowOutsideClick: false,
      didOpen: () => Swal.showLoading(),
    });

    try {
      setDownloadLeaflet(id);
      // 等待所有异步操作完成
      await downloadLeaflet({ id, title });
      await sendDownload({
        leafletId: id,
        recipient: null,
        type: 0,
      });
      setDownloadLeaflet(id);

      // 关闭加载弹窗,显示成功提示
      loadingPopup.close();
      Swal.fire('Downloaded!', 'Your file has been downloaded.', 'success');
    } catch (error) {
      // 关闭加载弹窗,显示错误提示
      loadingPopup.close();
      // 判断是否为网络中断错误
      const isNetworkIssue = !error.response || error.message.includes('Network Error');
      Swal.fire(
        'Download Failed',
        isNetworkIssue ? 'Network connection interrupted. Please try again later.' : 'Download failed. Please check your request and try again.',
        'error'
      );
    }
  }
};

关键优化点

  • 异步流程控制:用async/await替代链式then,让异步代码更易读,同时方便捕获所有异常
  • 加载状态显示:确认下载后立即弹出加载弹窗,禁用外部点击,通过Swal.showLoading()显示加载动画
  • 错误捕获与区分:
    • 捕获所有异步操作的异常,包括网络中断、请求失败等
    • 根据错误特征判断是否为网络问题,给出针对性提示
  • 弹窗生命周期管理:确保加载弹窗在操作完成(成功/失败)后关闭,再显示对应结果弹窗

内容的提问来源于stack exchange,提问作者Noor.Qidam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:13:35