Suppose I have some function that will output an alert() :

 var foo(err){ alert(err) } 

And let's say somewhere in the code, an error occurs with an undefined variable and an attempt to access its property:

Uncaught TypeError: Cannot read property 'x' of undefined

I can see this message in the console, but how to write a handler, or eventListener for the console? those. I want to pass an error message in the console to my foo() function, and I don’t have to wrap the required part of the code with conditions or use try catch .

    1 answer 1

    Found the answer, can someone come in handy

     window.addEventListener('error', function (e) { var error = e.error; foo(error); }); 
    • For good, it should never work. Own code - correct, someone else - catch try...catch . - user207618
    • 2
      @Other meaning never? Any error that occurs, this event, and just an error event, why should it not work? - Vasily Barbashev
    • @ Vasily Barbashev, this event is triggered only if the error is not intercepted. If it is intercepted, the event is not raised. Try to check for yourself if you do not believe. - user207618
    • @Other That's the point of this act of vandalism to log unprocessed errors. It is easy to say: “correct, catch try...catch ”, and is it easy to implement it, how to correct the error when you don’t even know about it ?? Thank you @ sanu0074. - GHosT