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

关于single-spa的系统无活动捕获与错误码捕获的技术咨询

关于single-spa的两个问题解答

1. 无活动超时重定向:single-spa无内置方法,需自行实现

single-spa本身并未提供内置的用户无活动检测或超时重定向功能,它的核心定位是微前端的加载、生命周期管理与路由协调,这类用户行为监控属于业务应用层逻辑。

你可以在根应用中实现全局的无活动超时逻辑(根应用是跨所有微前端的全局上下文,适合处理这类全局行为),具体实现方式:

  • 监听用户核心活动事件(如鼠标移动、键盘输入、点击、滚动等)
  • 设置15分钟的定时器,超时后触发重定向
  • 用户有任何活动时重置定时器
  • 可选:结合single-spa的应用生命周期钩子,在必要时暂停/恢复定时器

示例代码:

// 根应用中实现全局超时逻辑
let inactivityTimer;

// 重置定时器函数
const resetInactivityTimer = () => {
  clearTimeout(inactivityTimer);
  // 15分钟 = 15*60*1000毫秒
  inactivityTimer = setTimeout(() => {
    // 重定向到登录页或指定页面
    window.location.href = '/login';
  }, 15 * 60 * 1000);
};

// 绑定用户活动事件
['mousemove', 'keydown', 'click', 'scroll'].forEach(eventType => {
  window.addEventListener(eventType, resetInactivityTimer);
});

// 初始化定时器
resetInactivityTimer();

// 可选:如果需要在微前端卸载时清理定时器,可通过customProps传递
singleSpa.registerApplication({
  name: 'your-mfe',
  app: () => System.import('your-mfe'),
  activeWhen: () => true,
  customProps: {
    onUnmount: () => clearTimeout(inactivityTimer)
  }
});

2. 在addErrorHandler中捕获API错误码

single-spa的addErrorHandler会捕获微前端生命周期钩子(bootstrap、mount、unmount、update)中抛出的错误,包括这些钩子内部发起的API调用错误。你需要根据API请求库的错误结构来提取状态码:

针对Axios请求的错误捕获

Axios的错误对象包含response属性,其中status就是HTTP错误码:

singleSpa.addErrorHandler(error => {
  // 判断是否为Axios的API请求错误
  if (error.response) {
    const statusCode = error.response.status;
    console.error(`API请求失败,错误码:${statusCode}`);
    
    // 根据错误码执行对应逻辑,比如401跳转到登录页
    if (statusCode === 401) {
      window.location.href = '/login';
    }
  } else {
    // 处理其他类型的single-spa错误(如生命周期钩子同步错误)
    console.error('Single-spa生命周期错误:', error);
  }
});

针对Fetch请求的错误捕获

Fetch不会自动将HTTP错误状态码(如404、500)转为rejection,需要手动判断响应状态,再将错误抛给single-spa:

// 微前端生命周期钩子中的Fetch请求示例
async function mount(props) {
  const response = await fetch('/api/data');
  if (!response.ok) {
    // 将响应对象抛出,让addErrorHandler捕获
    throw response;
  }
  // 正常处理响应数据...
}

// 根应用中的错误处理
singleSpa.addErrorHandler(error => {
  if (error instanceof Response) {
    const statusCode = error.status;
    console.error(`API请求失败,错误码:${statusCode}`);
    // 执行对应逻辑...
  }
});

注意:组件内部的API错误捕获

如果API调用是在微前端的组件内部(而非single-spa生命周期钩子),addErrorHandler无法直接捕获这类错误。此时你可以:

  1. 在微前端内部自行处理错误
  2. 通过自定义事件将错误传递给根应用处理:
// 微前端组件中的错误处理
try {
  const res = await axios.get('/api/data');
} catch (err) {
  // 抛出自定义事件给根应用
  window.dispatchEvent(new CustomEvent('api-error', { detail: err }));
}

// 根应用中监听自定义事件
window.addEventListener('api-error', e => {
  const err = e.detail;
  const statusCode = err.response?.status;
  // 处理错误码逻辑...
});

内容的提问来源于stack exchange,提问作者user2613946

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:40:57