前端错误监控指南

作者:刘专,日期:2019 年 11 月 13 日

前端错误监控,最简单的方法是 window.onerror。它的签名如下:

window.onerror = function(
    message,    // error message
    source,     // URL of the script
    lineno,     // line number
    colno,      // column number
    error       // Error Object
) { ... };

由于历史原因,onerror 和 addEventListener 的函数签名不一样。

window.addEventListener('error', function(event){});

举个简单例子:

window.onerror = function(message, source, lineno, colno, error) {
    console.log('message:', message);
    console.log('source:', source);
    console.log('lineno:', lineno);
    console.log('colno:', colno);
    console.log('error:', error);
}

a = a / 2;

对于 Promise 异常,如果未被 catch,无法被 window.onerror 捕获。此时,需要监听 unhandledrejection 事件。比如

window.addEventListener('unhandledrejection', (event) => {
    event.preventDefault();
    console.log('Reason: ' + event.reason);
});

function foo() {
    Promise.reject('abc');
}

foo();

使用时,需要注意 unhandledrejection 事件的兼容性。具体数据参见 caniuse 网站。

跨域脚本错误

当加载自不同域的脚本中发生语法错误时,为避免信息泄露,语法错误的细节将不会报告,而代之简单的 “Script error.”。在某些浏览器中,通过在 <script> 使用 crossorigin 属性并要求服务器发送适当的 CORS HTTP 响应头,该行为可被覆盖。

REF

  1. GlobalEventHandlers.onerror - MDN
  2. JS错误监控总结深蓝一人,2018-04-30
  3. Window:unhandledrejection event - MDN
  4. Fundebug
  5. Tracking unhandled rejected Promises, by Dr. Axel Rauschmayer, 2016/04/12