关于前端:头大了我的Sentry为什么上报错误不准

3次阅读

共计 3947 个字符,预计需要花费 10 分钟才能阅读完成。

“瞎子过河记”

我的项目的监控报错机制应用 Sentry,为了更好的定位到谬误,所以须要上传 sourcemap

最终踩坑结束 Sentry 列表展现

  • 接口信息与页面报错辨别
  • 提供更多无效自定义 tag 帮忙疾速定位

分享一下我的踩坑之路(基础教程这里就不在反复了,网上一搜一大堆,给大家来点不一样的干货~)

坑 1:曾经上传 sourceMap 了然而只能看到报错,还是看不到源码。

const sentryConfig = {
  url: 'https://sentry.xxx.com/',
  authToken: '***',
  org: 'frontend',
  project: 'cms',
  release: version,
  sourceMaps: {include: ['./build/static/js'],
    ignore: ['node_modules'],
    urlPrefix: '~/sub-wechat/static/js',
  },
};

比方线上拜访地址是 https://www.**.com/sub-wechat/index urlPrefix 必须得在域名根目录下拜访到,所以必须设置为 ~/sub-wechat/static/js(sub-wechat/static/js 文件夹上面都是.js)

坑 2:终于能够看到源代码了,然而看到的源码是错行的,不是正确地位。Why?!

刚开始还狐疑 Sentry 的问题,本着我做了完我没有错,甩锅哈哈哈哈哈。
起初吃了个晚饭沉着了下来认真排查发现浏览器查看报错也是错的,最初发现罪魁祸首,懒加载 css。 到当初也没搞懂为什么这个会影响 sourcemap 报错地位??求问

https://github.com/vitejs/vit…

为什么要对立封装 Sentry

  • 我的项目多了上报信息谬误不对立
  • 被动上报谬误(比方 log、warn、debug、fatal、error)
  • TAG 上报的信息等级对立

为什么要监控接口谬误

  • 谬误监控及日志排查,提供更多无效信息;
  • 接口异样状态,依据异样状态发现代码的破绽;
  • 有对立的一个 request SDK,解决起来非常简单,

    sentry.js
    import * as Sentry from '@sentry/browser';
    import {Integrations} from '@sentry/tracing';
    /**
     * fatal: 很重大的零碎异样,零碎无奈持续运行,必须解决,重要级别与 uncaught 的 error 相似
     * error(默认值): 零碎异样,无奈失常运行,如果 type 是 uncaught,该报错必须由开发人员确定是否须要修复,如果是 caught,示意可预感的报错,看状况解决
     * debug: 帮助解决线上问题
     * warn: 零碎可持续运行上来,用户可持续操作,用于上报一些警示线的错误信息
     * log: 简略的日志打点
     */
    
    /**
     * @description sentry 的初始化配置,仅在线上及 beta 环境进行
     * @param {string} env 环境
     * @param {string} dsn sentry 生成的 dsn 值。* @param {string} release 我的项目版本
     * @param {array} tags Sentry 对应的 tags
     * @examplenpm r
     *
     * Capture.init({env: 'production', dsn: '1231afaf1', release: '1.0.0', tags: {TIME: new Date()})
     *
     */
    
    const Severity = {
    Fatal: 'fatal',
    Error: 'error',
    Warning: 'warning',
    Log: 'log',
    Info: 'info',
    Debug: 'debug',
    };
    class Capture {constructor(options) {
      const {
        env,
        dsn,
        release,
        tags,
      } = options;
      if (env === 'production') {
        Sentry.init({
          dsn,
          release,
          integrations: [new Integrations.BrowserTracing()],
          tracesSampleRate: 1.0,
          beforeSend(event) {const { exception} = event;
            // 接口申请谬误被动上报了,这里就间接疏忽掉
            const requestErr = exception.values.find((item) => item.value.startsWith('Request failed with status code'));
            if (requestErr) return null;
            const sendUser = event;
            // 在这里可依据业务状况发送用户信息
            const userData = localStorage.getItem('userData');
            let user = {
              cellphone: null,
              realName: null,
            };
            if (userData) {const userObj = JSON.parse(userData);
              user = {
                cellphone: userObj.cellphone,
                realName: userObj.realName,
                company: userObj.manageDepartmentNames,
                companyId: userObj.companyId,
              };
            }
            sendUser.user = user;
            return event;
          },
          ignoreErrors: [
            'Failed to fetch',
            'NetworkError when attempting to fetch resource.',
            'ResizeObserver loop limit exceeded',
            'ResizeObserver loop completed with undelivered notifications',
            'Loading chunk',
            'Unable to preload CSS for',
            'Request aborted',
          ],
        });
    
        Sentry.configureScope((scope) => {const date = new Date();
          const ymdDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
          const hour = date.getHours().toString();
          scope.setTag('ERRORTYPE', 'uncaught');
          scope.setTag('ENV', env);
          scope.setTag('DATE', ymdDate);
          scope.setTag('HOUR', hour);
          scope.setLevel(Severity.Error);
          if (tags && typeof tags === 'object') {Object.keys(tags).forEach((key) => {scope.setTag(key, tags[key]);
            });
          }
        });
      }
    }
    
    // eslint-disable-next-line class-methods-use-this
    sentryCapture({
      error = '',
      extra,
      level,
      tags,
    }) {Sentry.withScope((scope) => {scope.setTag('ERRORTYPE', 'caught');
        scope.setLevel(level);
        let reportError = error;
        if (error instanceof Error) {reportError = error.toString();
        } else if (typeof error === 'object') {reportError = JSON.stringify(error);
        }
    
        if (extra && typeof extra === 'object') {Object.keys(extra).forEach((key) => {scope.setExtra(key, extra[key]);
          });
        }
    
        if (tags && typeof tags === 'object') {Object.keys(tags).forEach((key) => {scope.setTag(key, tags[key]);
          });
        }
        if (reportError === 'CANCEL') return;
        Sentry.captureException(new Error(reportError));
      });
    }
    
    fatal(param) {this.sentryCapture({ ...param, level: Severity.Fatal});
    }
    
    error(param) {this.sentryCapture({ ...param, level: Severity.Error});
    }
    
    warn(param) {this.sentryCapture({ ...param, level: Severity.Warning});
    }
    
    debug(param) {this.sentryCapture({ ...param, level: Severity.Debug});
    }
    
    log(param) {this.sentryCapture({ ...param, level: Severity.Log});
    }
    }
    
    export default Capture;
    

    应用

    import Capture from 'sentry.js';
    
    const capture = new Capture({
      dsn: '*****',
      release: version,
      env: import.meta.env.MODE,
    });

求教下大神 为什么懒加载会影响 sourceMap 地位?

正文完
 0