是否可以覆盖控制台日志

时间:2014-05-23 22:36:14

标签: javascript error-handling console.log

如果我从框架收到错误或从浏览器收到错误。基本上是任何类型的运行时错误。在不修改框架的情况下,我是否可以覆盖这些框架所做的控制台日志以及浏览器的错误。我想在告知用户几乎所有运行时(而不是语法错误)的错误时,使用我自己的框架和自己的错误处理系统。我不知道你是否会将它全部归为运行时错误,因为javascript在浏览器中的执行方式但希望你能得到我?

如果所有框架都是用Javascript编写的,这可能吗?

这是如何实现的?

我必须在不同浏览器之间做出哪些考虑?

由于

5 个答案:

答案 0 :(得分:1)

您可能正在寻找try-catch block

try {
    alert(foo);
} catch(e) {
    alert('The code got the following error: '+e.message);
}

每当try {}之间的代码收到错误时,catch(e) {}块就会执行,参数e是发生错误的错误对象。在这种情况下,变量foo未定义,因此执行此代码将导致警告消息“代码出现以下错误:foo未定义

答案 1 :(得分:1)

虽然没有超越console.log,但您可以通过覆盖window.onerror来达到同样的效果。

来自MDN documentation

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
    // Log the error here -- perhaps using an AJAX call
}

答案 2 :(得分:0)

您可以尝试覆盖console.log()功能。

//Save original reference
var originalConsole = console;
//Override
console = {};
console.log = function()
{
    //According to MDN the console.log function can receive a variable number of params
    for(var i=0; i<arguments.length; i++)
    {
        //Make your changes here, then call the original console.log function
        originalConsole.log("Change something: "+arguments[i]);
    }
    //Or maybe do something here after parsing all the arguments
    //...
}

console.log("one", "two");

JSFiddle here

答案 3 :(得分:0)

您可以通过创建“控制台”对象并覆盖它的.log()函数来覆盖控制台日志:

var console = {};
console.log = function(){};

有些浏览器要求将其直接添加到窗口对象中;因此,为了兼容浏览器,还要添加:

window.console = console;

此外,如果你也使用它们,你可以覆盖其他控制台功能(例如console.info,console.warn和console.error)。

另外,请考虑在覆盖控制台功能时阅读Udi Talias的this blog post。好快速阅读!

答案 4 :(得分:0)

您可以在此处自定义console.log

// copy the original
let originalConsole = Object.assign({}, console);
// do something with your log.
            console.log = (value) => {
                //some cool condition
                if (true) {
                    value = "new_log : " + value
                }
                originalConsole.log(value);
            };