简体   繁体   English

使用javascript检查特定控制台错误是否发生/存在

[英]Checking if specific console error occurred/exists with javascript

I would like to check if a certain console error has occurred using javascript, and alert() myself if it has. 我想检查是否使用javascript发生了某个控制台错误,如果有的话,我自己使用alert()

The error will look like this: 该错误将如下所示:

00:00:34:0359 TimeEvent.COMPLETE
    (anonymous function) @ VM17617:1

And the algorithm will look something like this: 该算法将如下所示:

function checkError(console) {
    if(console.error === "TimeEvent.COMPLETE") {
        alert("The error is present");
    }
}

I'm not very familiar with the console, and haven't gotten much further with Google research. 我对控制台不是很熟悉,对Google的研究还不够。 Can somebody point me in the right direction? 有人可以指出我正确的方向吗?

I ultimately solved my question by following this blog post on taking over the console with javascript. 我最终通过关注此博客文章 (用JavaScript接管控制台)解决了我的问题。

Here is my final code: 这是我的最终代码:

var original = window.console
window.console = {
    error: function(){      

        //Gets text from error message.
        errorText = arguments['0'];

        if (errorText.includes('TimeEvent.COMPLETE')) {
            //DO STUFF HERE
        }

        original.error.apply(original, arguments)
    }
}

You didn't provide the whole picture about how and when the console is getting the error. 您没有提供有关控制台如何以及何时收到错误的全部信息。 If you raise the error yourself, or if you are able to catch it inside a try catch , that would be the best place to intercept those errors. 如果您自己引发错误,或者能够在try catch该错误,那将是拦截这些错误的最佳位置。

However, if you have no control about how those error are raised, you should try to intercept your console's error calls. 但是,如果您无法控制如何引发这些错误,则应尝试拦截控制台的错误调用。 I never tried it myself but this SO answer explains how to intercept the console's log calls. 我从未亲自尝试过,但是这个答案解释了如何拦截控制台的log调用。 Knowing that the console usually have a function named error that is similar to the log function, I'm sure you could apply the same logic to intercept the errors sent to the console. 知道控制台通常有一个名为error的函数,它类似于log函数,因此我确定您可以应用相同的逻辑来拦截发送到控制台的错误。

If you are using chrome, you may refer to the console documentation for more details about the error function. 如果您使用的是chrome,则可以参考控制台文档以获取有关错误功能的更多详细信息。 I'm not sure if there's a standard but Internet Explorer and Firefox also has support for console error function. 我不确定是否有标准,但是Internet ExplorerFirefox也支持控制台error功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM