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

如何捕获WebComponent微前端包中的Sentry错误?

解决WebComponent微前端包内错误的Sentry捕获问题

一、全局错误监听兜底

WebComponent内部的未捕获错误会冒泡到window层面,直接加全局事件监听手动喂给Sentry就行:

// 捕获同步错误
window.addEventListener('error', (event) => {
  // 只处理微前端包的错误
  if (event.filename.includes('microfrontend-1.umd.js')) {
    Sentry.captureException(event.error, {
      tags: { source: 'microfrontend-webcomponent' },
      extra: {
        filename: event.filename,
        line: event.lineno,
        column: event.colno
      }
    });
  }
});

// 捕获未处理的Promise拒绝
window.addEventListener('unhandledrejection', (event) => {
  if (event.reason?.stack?.includes('microfrontend-1.umd.js')) {
    Sentry.captureException(event.reason, {
      tags: { source: 'microfrontend-webcomponent' }
    });
    event.preventDefault(); // 可选:阻止默认控制台报错
  }
});

二、调整Sentry全局配置

检查宿主的Sentry初始化配置,别把微前端的URL给排除了:

Sentry.init({
  // 其他基础配置(DSN、环境等)
  allowUrls: [
    /host\.io/,
    /microfrontend\.io\/base\/url\/microfrontend-1\.umd\.js/
  ],
  // 如果之前配置了ignoreUrls,确保没包含微前端的地址
  ignoreUrls: []
});

三、微前端主动捕获的修正

你在StaticPage.vue和StaticPages.ts里主动调用Sentry.captureException没生效,大概率是微前端里没复用宿主的Sentry实例。直接改微前端代码,用全局的window.Sentry:

// StaticPages.ts里的主动上报
window.Sentry?.captureException('oh no!');

// StaticPage.vue里的错误捕获
try {
  // 你的业务代码,比如可能抛出错误的逻辑
} catch (err) {
  window.Sentry?.captureException(err);
}

另外,微前端打包时要把Sentry设为外部依赖,别打包进去,用宿主的实例。比如在微前端的vite.config.ts里加:

export default defineConfig({
  build: {
    lib: {
      entry: 'src/main.ts',
      name: 'Microfrontend1',
      fileName: 'microfrontend-1.umd'
    },
    rollupOptions: {
      external: ['@sentry/browser'], // 把Sentry标记为外部依赖
      output: {
        globals: {
          '@sentry/browser': 'Sentry' // 映射到全局的Sentry
        }
      }
    }
  }
});

四、配置SourceMap让错误来源显示正确

要让Sentry显示错误来自microfrontend-1.umd.js,得上传微前端的sourcemap:

  1. 微前端打包时开启sourcemap:
// 微前端的vite.config.ts
export default defineConfig({
  build: {
    sourcemap: true // 生成sourcemap文件
  }
});
  1. 用Sentry CLI把sourcemap传到Sentry后台,注意对应好URL前缀:
sentry-cli releases files <你的版本号> upload-sourcemaps ./dist --url-prefix 'https://microfrontend.io/base/url/'

五、验证效果

在微前端的StaticPage.vue里加个测试按钮,故意抛错:

<template>
  <button @click="triggerError">测试错误上报</button>
</template>
<script setup>
const triggerError = () => {
  throw new Error('client error');
};
</script>

点击按钮后去Sentry后台看,应该能收到错误,且来源标记为microfrontend-1.umd.js;同时主动调用的window.Sentry.captureException('oh no!')也能正常上报。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:30:14