Invalid JavaScript / window.onerror msg exception handler

I need to catch one type of error that can occur in many different pages / scripts and execute user logic when this error occurs. I planned to use

window.onerror = function (msg, url, line) { if ({{my specific error happened}}){ {{do some custom work}}; return true; } //do nothing and let the browser notify the user of all the other errors } 

so that I can do throw {{my specific error}} and catch it in window.onerror . I tried throw "Magic"; but then in window.onerror I get msg == "Uncaught Magic" . Will this "Unclean" part of msg always precede my abandoned line? Can I rely on him to discover my specific mistake? Or is there some other mechanism for detecting the type of error in window.onerror ?
I only need this to work in Chromium.

+4
source share
1 answer

Some browsers now send the actual error object. Not sure which browsers support this. It says that Gecko 31 is required. I don’t know how chrome and others are.

You can create a custom error, for example:

 Magic = function( message ) { this.name = 'Magic'; this.message = message; } Magic.prototype = new Error(); Magic.prototype.constructor = Magic; 

throw it somewhere:

 throw new Magic('Kaboom'); 

and catch it in window.onerror as follows:

 window.onerror = function ( message, filename, lineno, colno, error ){ if ( error !== undefined && error.hasOwnProperty( "name" ) && error.name == "Magic"){ alert("some uncaught magic caused: " + message +" - in "+filename +"("+lineno+")" ); return true; } } 

check fiddle **


you can also check if the message contains “Magic”, but then you can accidentally catch other errors containing “Magic”.


ps: sorry for necro, I stumbled upon this search of the same .. so I thought I could add an answer.

+3
source

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


All Articles