获取页面上的所有 javascript 错误/javascript 错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6970475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:02:30  来源:igfitidea点击:

Get all javascript errors on page/javascript error handling

javascript

提问by Devin G Rhode

I want to be able to send myself all the javascript errors on a page. I am an extension developer, so the following has an emphasis on making sure the dom is ready before making calls to it.

我希望能够向自己发送页面上的所有 javascript 错误。我是一名扩展开发人员,因此以下重点是确保在调用 dom 之前已准备好。

I investigated adding some functionality to the throwto also send or mail the exceptions, but I didn't find this to be possible.

我调查了向 中添加一些功能以throw发送或邮寄异常,但我认为这是不可能的。

1:main solution to this, a window.onerror handler:

1:对此的主要解决方案,一个window.onerror 处理程序

window.onerror = function(e, url, line){
  mailError('onerror: ' + e + ' URL:' + url + ' Line:' + line);
  console.error('\nLine ' + line + ':');
  setTimeout(function(){retry();}, 100); //mainly useful in content scripts for extensions, 
  return true; 
}

May also need to do same thing via jQuery:

可能还需要通过 jQuery 做同样的事情:

$(window).error( 
  function(e, url, line){
    //handle error
  }
);

The downfall of this is that your code has stopped executing.

这样做的缺点是您的代码已停止执行。

To avoid errors stopping execution, it's best to use callbacks to make sure code executes in a certain sequence, and to utilize events wherever possible. You can also protect dom calls with a few techniques

为了避免错误停止执行,最好使用回调来确保代码按特定顺序执行,并尽可能利用事件。您还可以使用一些技术来保护 dom 调用

$(document).ready({
  //you usually won't get bad dom calls wrapping your code in this
});

You can also consider running code on window.onload

你也可以考虑在 window.onload 上运行代码

window.onload = function(){
  //you page will probably twitch upon executing code at this time
  //but you will almost never have a bad dom call
};

Another technique

另一种技术

if (document.getElementById('iNeedThisElement')) {
  //doin work!
  document.getElementById('iNeedThisElement').style.display = 'block';
} else {
  var stillNeedToTakeCareOfX = true; //false otherwise since it's undefined
  mailError('iNeedThisElement was unavailable...');
}

Using these techniques and just debugging your application, you should be fairly well off. Since console.error, .warn, and .log statements cannot be retrieved and reported back to your, a small alternative suite is provided below:

使用这些技术并仅调试您的应用程序,您应该会相当不错。由于无法检索 console.error、.warn 和 .log 语句并将其报告给您,因此下面提供了一个小的替代套件:

var Xe = { }; //Extreme error suite

function extraInfo(e){
   //e optional
   if(!e)e = true;

   //add an extra debug info, such as navigator or current URL
   return ' currentURL: '+ document.URL + 
        '\n userAgent: ' + navigator.userAgent + 
        '\n platform: '  + navigator.platform + 
        '\n userid: '    + localStorage.userid + 
        '\n language: '  + navigator.langauge + 
        '\n cookies?: '  + navigator.cookiesEnabled;
}

Xe.error = function(e){
  console.error(e); //maintain original functionality
  mailError('Xe err: ' + e + extraInfo() );
}


Xe.warn = function(e){
  console.warn(e);
  mailError('Xe warn: ' + e + extraInfo() );
}


Xe.log = function(e){
  console.log(e);
  mailError('Xe log: ' + e + extraInfo() );
}

As a last ditch, you can continually attempt to execute a chunk of code until it executes without errors. This is "2" below.

作为最后一搏,您可以不断尝试执行一段代码,直到它无误地执行为止。这是下面的“2”。

2:group code in large chunks and attempting to re-execute x seconds later after catching an error, or continue to next chunk of code

2:将代码分成大块并尝试在捕获错误后 x 秒后重新执行,或继续执行下一个代码块

//defExe = DEFinitely EXEcute this code
  //functionArg, reference to a function holding a large chunk of code
  //seconds, timeout in milliseconds to re-attempt error free execution of this function
function defExe(functionArg, seconds) {
  //seconds is optional
  if (!seconds)seconds = 300;

  try {
    functionArg();
  } catch(e) {
    //mail the error plus extra info
    mailError('caught ' + e + ' attempting to re-execute ' + functionArg.name + ' in ' + seconds + ' milliseconds');

    //re-attempt to execute this code
    setTimeout(function(){ 
       defExe(functionArg, seconds); 
    }, seconds);
  }
}

this it is then used like

然后使用它

//array to group function chunks
var fn = [ ];

fn[1] = function (){
  //a large chunk of javascript
}
defExe(fn[1]);

fn[2] = function(){
  //another chunk of your program
}
defExe(fn[2]);

#2 Summary: Group code in functions and run in try-catch block, repeating if an errors are caught

#2 总结:在函数中分组代码并在 try-catch 块中运行,如果捕获到错误则重复

回答by Sergi Ramón

I have mine working with window.onerror and it doesn't stop my javascript:

我有我的 window.onerror 工作,它不会停止我的 javascript:

window.onerror = function(error, url, line) {
    controller.sendLog({acc:'error', data:'ERR:'+error+' URL:'+url+' L:'+line});
};

Note that controller.sendLog is a function that sends this data to a logging php.

请注意,controller.sendLog 是一个将此数据发送到日志记录 php 的函数。

Can be because you're causing some javascript error inside that function?

可能是因为您在该函数中导致了一些 javascript 错误?

回答by Pascal Trouvin

Sorry but try/catch will catch only code errors, never load error (if a file is missing or something that).

抱歉,try/catch 只会捕获代码错误,永远不会加载错误(如果文件丢失或其他错误)。

window.onerror / $(window).error is definitely the best solution.

window.onerror / $(window).error 绝对是最好的解决方案。

回答by Justin Beckwith

When an exception is raised in most languages, execution of the current command stack is going to be stopped. So your global window.onerror approach works, but doesn't continue to execute code after a failure. I'm curious why you would expect a retry to work in the case that the original call fails? Maybe there's another way to optimize your application to avoid this.

当在大多数语言中引发异常时,将停止当前命令堆栈的执行。因此,您的全局 window.onerror 方法有效,但在失败后不会继续执行代码。我很好奇为什么您希望在原始调用失败的情况下重试工作?也许有另一种方法可以优化您的应用程序以避免这种情况。

One of the things I like to do is wrap any of my code in window.onerror function in a try catch block. In the catch statement (last resort) I will generally use an alert of some sort, just in case something goes catastrophically wrong. The idea here is that you don't want your error handling for the page to EVER end up causing another error to be launched.

我喜欢做的一件事是将我的任何代码包装在 window.onerror 函数中的 try catch 块中。在 catch 语句(最后的手段)中,我通常会使用某种警报,以防万一出现灾难性的错误。这里的想法是您不希望页面的错误处理最终导致启动另一个错误。

回答by The Fire TITAN

You can try also

你也可以试试

Try...Catch Statement

Try...Catch 语句

try  
{  
  //Run your code here
}
catch(err)
{
  //Handle the errors here
}