Can I override console logs?

If I get an error from a framework or an error in the browser. Basically, a runtime error. Without changing the scope, I can override the console logs that these frameworks do and browser errors. I want to use my own framework with my own error handling system when informing the user about errors of almost any runtime (and not syntax errors). I don’t know if you will classify all this as runtime errors due to the way javascript is executed in the browser, but hopefully you get me?

Is this possible if all the frameworks are written in Javascript?

How is this achieved?

What considerations should I do between different browsers?

thank

+4
source share
4 answers

You can try to override the function 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 .

0
source

You may be looking for try-catch:

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

Whenever the code between try {}receives an error, a block will be executed catch(e) {}, and the argument eis the object of the error for the error that occurred. In this case, the variable is foonot defined, so the execution of this code will result in the warning message "The code received the following error: foo not defined"

+1
source

console.log, , window.onerror.

MDN

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

, "" .log():

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

, ; :

window.console = console;

, (, console.info, console.warn console.error), .

, Udi Talias . !

0

Source: https://habr.com/ru/post/1541832/


All Articles