Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

26、前端错误信息采集 #26

Open
shengq666 opened this issue Feb 1, 2021 · 2 comments
Open

26、前端错误信息采集 #26

shengq666 opened this issue Feb 1, 2021 · 2 comments

Comments

@shengq666
Copy link
Owner

No description provided.

@shengq666
Copy link
Owner Author

前端所能捕捉的错误主要有三种:

  • 资源加载错误,通过 addEventListener('error', callback, true) 在捕获阶段捕捉资源加载失败错误。
  • js 执行错误,通过 window.onerror 捕捉 js 错误。
  • promise 错误,通过 addEventListener('unhandledrejection', callback)捕捉 promise 错误,但是没有发生错误的行数,列数等信息,只能手动抛出相关错误信息。

@shengq666
Copy link
Owner Author

shengq666 commented Feb 1, 2021

创建一个错误数组变量 errors ,在错误发生时,将错误的相关信息添加到数组,然后在某个阶段统一上报或者实时上报。

// 捕获资源加载失败错误 js css img...
addEventListener(
  'error',
  (e) => {
    const target = e.target
    if (target != window) {
      monitor.errors.push({
        type: target.localName,
        url: target.src || target.href,
        msg: (target.src || target.href) + ' is load error',
        // 错误发生的时间
        time: new Date().getTime(),
      })
    }
  },
  true
)

// 监听 js 错误
window.onerror = function (msg, url, row, col, error) {
  monitor.errors.push({
    type: 'javascript',
    row: row,
    col: col,
    msg: error && error.stack ? error.stack : msg,
    url: url,
    // 错误发生的时间
    time: new Date().getTime(),
  })
}

// 监听 promise 错误 缺点是获取不到行数数据
addEventListener('unhandledrejection', (e) => {
  monitor.errors.push({
    type: 'promise',
    msg: (e.reason && e.reason.msg) || e.reason || '',
    // 错误发生的时间
    time: new Date().getTime(),
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant