您如何将控制台消息和错误发送到警报? [英] How do you send console messages and errors to alert?

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

问题描述

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

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(scripts) 试过了.

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.

我尝试猴子修补控制台错误:

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,什么函数在真正错误的情况下将错误发送到控制台?我可以访问它并更改它吗?有任何想法吗?帮助将不胜感激.谢谢珍妮塔

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 所说,它不会捕获 Syntax错误,而且它不会捕获回调函数抛出的错误,后者稍后执行(在 try-catch 完成后很久).这意味着传递给 setTimeoutaddEventListener 的任何函数都没有错误.

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.

不顾一切地捕捉行号,我开始试验 setTimeoutaddEventListener 的包装器,它们将围绕这些调用重新引入 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天全站免登陆