如何发送控制台消息和错误以提醒? [英] How do you send console messages and errors to alert?

查看:135
本文介绍了如何发送控制台消息和错误以提醒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将错误传递给警报,以警告用户他们在代码中出错,即使他们没有控制台打开。

I would like to pass errors to an alert to warn the user they made mistake in their code even if they don't have console open.

    var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow);
    var head = doc.getElementsByTagName('head')[0];
    var scriptElement = doc.createElement('script');
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.text = scripts;

    try{
        head.appendChild(scriptElement);
    }
     catch(e){ alert("error:"+e.message +"  linenumber:"+e.lineNumber);}

当脚本包含错误时,appendChild会引发错误。它直接进入控制台,我希望它显示在一个警报,因为它是为孩子,他们可能不检查控制台。 try catch块不能捕获错误。
我用eval(脚本)试了一下。

The appendChild throws an error when the scripts contain an error. It goes straight to the console though, and I want it to display in an alert, because it is for kids and they might not check the console. The try catch block does not catch the error. I tried it with eval(scripts).

   try{
   eval(scripts);} catch(e){ alert("error:"+e.message +"  linenumber:"+e.lineNumber);}

这样做有效,但这意味着代码执行两次,这在某些情况下非常不方便。

this does work but it means that the code is executed twice, and that is very inconvenient in some cases.

我尝试了猴子修补console.error :

I tried monkey patching the console.error:

       console.log=function(){alert("taking over the log");}
       console.error=function(){alert("taking over the log");}

当我真的使用console.error。不是当一个实际的错误被抛出。
在出现真实错误的情况下,如果不是console.error,什么函数将错误发送到控制台?我可以访问它并更改它吗?
任何想法?帮助将非常感激。
感谢Jenita

but that only works when I literally use console.error. Not when an actual error is thrown. What function sends the error to the console in the case of a real error,if it isn't console.error? and can I access it and change it? Any ideas? Help would be really appreciated. Thanks Jenita

推荐答案

虽然 try ... catch 将处理脚本最初运行的代码,因为Jenita说它不会捕获语法错误,而且也不会捕获稍后执行的回调函数抛出的错误(很久以后, catch已经完成)。这意味着任何函数都不会传递给 setTimeout addEventListener

Whilst try ... catch will work on the code that the script runs initially, as Jenita says it won't catch Syntax Errors, and also it won't catch errors thrown by callback functions which execute later (long after the try-catch has finished). That means no errors from any functions passed to setTimeout or addEventListener.

但是,您可以尝试其他方法。在窗口上注册错误侦听器。

However, you can try a different approach. Register an error listener on the window.

window.addEventListener("error", handleError, true);

function handleError(evt) {
    if (evt.message) { // Chrome sometimes provides this
      alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
    } else {
      alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
    }
}

当一个异常从回调函数。但是它也会触发一般的DOM错误,如图像无法加载,您可能不感兴趣。

This will be called when an exception is thrown from a callback function. But it will also trigger on general DOM errors such as images failing to load, which you may not be interested in.

它也应该触发语法错误,但只有当它能够运行第一个,所以你应该把它放在一个单独的脚本可能包含打字错误! (脚本后面的语法错误将阻止相同脚本顶部的有效行运行。)

It should also fire on Syntax Errors but only if it was able to run first so you should put it in a separate script from the one that may contain typos! (A Syntax Error later in a script will prevent valid lines at the top of the same script from running.)

不幸的是,我从来没有找到一种方法来获取行号从Firefox中的 evt

Unfortunately, I never found a way to get a line number from the evt in Firefox. ( Poke around, I think it might be there now.)

我发现当尝试写入 FastJSLogger ,当浏览器devtools稍慢时,我使用的页内记录器。

I discovered this when trying to write FastJSLogger, an in-page logger I used back when the browser devtools were somewhat slow.

绝望地捕捉行号,我开始实验,包含 setTimeout的包装器 addEventListener ,这将重新引入这些调用的try-catch。例如:

Desperate to catch line numbers, I started to experiment with wrappers for setTimeout and addEventListener that would re-introduce try-catch around those calls. For example:

var realAddEventListener = HTMLElement.prototype.addEventListener;

HTMLElement.prototype.addEventListener = function(type,handler,capture,other){
    var newHandler = function(evt) {
        try {
            return handler.apply(this,arguments);
        } catch (e) {
            alert("error handling "+type+" event:"+e.message +"  linenumber:"+e.lineNumber);
        }
    };

    realAddEventListener.call(this,type,newHandler,capture,other);
};

显然,这应该在任何事件监听器注册之前完成,甚至可能在加载jQuery之类的库之前,以防止它们在我们能够替换之前获取对真实的 addEventListener 的引用。

Obviously this should be done before any event listeners are registered, and possibly even before libraries like jQuery are loaded, to prevent them from grabbing a reference to the real addEventListener before we have been able to replace it.

这篇关于如何发送控制台消息和错误以提醒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆