Is there a way to intercept ALL JavaScript errors? - javascript

Goal: When any JS error occurs, grab the information from that error and execute a custom function with it.
Description: If a script creates an error like this...
var a = test;
// VM334:1 Uncaught ReferenceError: test is not defined
...how can I "intercept" that error; perhaps something like this:
Error.onerror = function(e){ alert("The error is " + e ); }
// "The error is VM334:1 Uncaught ReferenceError: test is not defined"
Note:
I am aware of the following:
window.onerror = function(){...}
window.addEventListener('error', ... )
Unfortunately these do not get the job done for reasons I believe are related to scope. I believe many errors will fail to be tracked because they do not live on the window object.
try{}catch(e){alert(e)} is also not a solution because it is too particular about where the errors come from.
I have also tried overwriting console.error but this function is not called when a JS error occurs on page.
Is there a way to respond to ANY JS error?
Cheers

Related

How to use a user's submitted code, and get its errors to have relevant info?

So I'm creating a mod for the singleplayer browser game Cookie Clicker. In my mod I allow the user to insert in their own code to do their own special things to interact with my mod's main function.
However, when the user codes on my custom editor, I want to "test" their code before they save to make sure no errors happen, and if they do, display a error message with what they did and where they did it. Getting the error is easy with a try/catch. But I noticed the error message is:
SynaxError: missing ) after argument list
at new Function (<anonymous>)
at HTMLAnchorElement.save.onclick (chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/userscript.html?name=Building%2520Sorter.user.js&id=18320655-b018-42e2-8fa5-7fb0cc8d2d70:578:24)
Which isn't helpful for me at all. The most I could salvage from this is the first line. However, that doesn't tell the user at all where the error is located in their code.
the 578:24 that points to the supposed error is:
try{
//code.value is a STRING of the user's code
let func = new Function(code.value);//<-- error points here in my source code.
func.call(null, [[0, 1, 2], Game]);
save.classList.remove('ModBuildingSorter_unsaved');
}
catch(e){
console.dir(e);
}
What I would like to happen is when the user sumbits:
return function(array){
return array.sort(function(building1,building2){
return building1.price - building2.price;
};// missing array.sort closing parenthesis
}
get's ran, I can get a syntax error telling me it's on line 4
Is there a way I can do this? Make the user's code act kinda like it's own file and try running it so I can find out which row & column the error is located?
You could, in theory, run the function from an eval()
i.e.:
try {
let a = "function test(o){console.lo(o)}test('hello');" // Minified function
eval(a)
} catch (e) {
console.log(e)
}
Here is the unminified function for example purposes:
function test(o)
{
console.lo(o) // <-- Error
}
test('hello');
and this returns the error correctly, which is
TypeError: console.lo is not a function
at test (eval at <anonymous> (D:\StackOverflowSandbox\index.js:3:5), <anonymous>:1:26)
Hope I've helped.

CKEditor uncaught type error

I am trying to run
CKEDITOR.instances.textareaid.setReadOnly(true);
or
CKEDITOR.instances["textareaid"].setReadOnly(true);
I get an error in the console saying
Uncaught TypeError: Cannot read property 'setReadOnly' of undefined
However if I run the same statements in the console, it executes without error.
If I put a debugger before the statements and inspect the CKEDITOR object, the instance is present, still it throws the error.
Try this sample
https://sdk.ckeditor.com/samples/readonly.html
This is may be that your ckeditor is not fully loaded. below event fires once the editor is fully loaded, so is probably where you would like to tie into. try this may be this will help u
if ( CKEDITOR.status == 'loaded' ) {
// The API can now be fully used.
CKEDITOR.instances["textareaid"].setReadOnly(true);
}
// Or
CKEDITOR.on("instanceReady", function(event)
{
CKEDITOR.instances["textareaid"].setReadOnly(true);
});

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.
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. 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.
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.
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. 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.
If you are using chrome, you may refer to the console documentation for more details about the error function. I'm not sure if there's a standard butInternet Explorer and Firefox also has support for console error function.

How do you send console messages and errors to alert?

I would like to pass errors to an alert to warn the user they made mistake in their code even if they don't have console open.
var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow);
var head = doc.getElementsByTagName('head')[0];
var scriptElement = doc.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.text = scripts;
try{
head.appendChild(scriptElement);
}
catch(e){ alert("error:"+e.message +" linenumber:"+e.lineNumber);}
The appendChild throws an error when the scripts contain an error. It goes straight to the console though, and I want it to display in an alert, because it is for kids and they might not check the console. The try catch block does not catch the error.
I tried it with eval(scripts).
try{
eval(scripts);} catch(e){ alert("error:"+e.message +" linenumber:"+e.lineNumber);}
this does work but it means that the code is executed twice, and that is very inconvenient in some cases.
I tried monkey patching the console.error:
console.log=function(){alert("taking over the log");}
console.error=function(){alert("taking over the log");}
but that only works when I literally use console.error. Not when an actual error is thrown.
What function sends the error to the console in the case of a real error,if it isn't console.error? and can I access it and change it?
Any ideas? Help would be really appreciated.
Thanks Jenita
Whilst try ... catch will work on the code that the script runs initially, as Jenita says it won't catch Syntax Errors, and also it won't catch errors thrown by callback functions which execute later (long after the try-catch has finished). That means no errors from any functions passed to setTimeout or addEventListener.
However, you can try a different approach. Register an error listener on the window.
window.addEventListener("error", handleError, true);
function handleError(evt) {
if (evt.message) { // Chrome sometimes provides this
alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
} else {
alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
}
}
This will be called when an exception is thrown from a callback function. But it will also trigger on general DOM errors such as images failing to load, which you may not be interested in.
It should also fire on Syntax Errors but only if it was able to run first so you should put it in a separate script from the one that may contain typos! (A Syntax Error later in a script will prevent valid lines at the top of the same script from running.)
Unfortunately, I never found a way to get a line number from the evt in Firefox. (Edit: Poke around, I think it might be there now.)
I discovered this when trying to write FastJSLogger, an in-page logger I used back when the browser devtools were somewhat slow.
Desperate to catch line numbers, I started to experiment with wrappers for setTimeout and addEventListener that would re-introduce try-catch around those calls. For example:
var realAddEventListener = HTMLElement.prototype.addEventListener;
HTMLElement.prototype.addEventListener = function(type,handler,capture,other){
var newHandler = function(evt) {
try {
return handler.apply(this,arguments);
} catch (e) {
alert("error handling "+type+" event:"+e.message +" linenumber:"+e.lineNumber);
}
};
realAddEventListener.call(this,type,newHandler,capture,other);
};
Obviously this should be done before any event listeners are registered, and possibly even before libraries like jQuery are loaded, to prevent them from grabbing a reference to the real addEventListener before we have been able to replace it.
Ok so the less elegant but highly efficient way of doing this is 'refactoring' your innate console functions. Basically any error or warnings you get are being outputted there by a javascript function that is pretty similar to the familiar console.log() function. The functions that I am talking about are console.warn(), console.info() and console.error(). now let's 're-map' what each of those do:
//remap console to some other output
var console = (function(oldCons){
return {
log: function(text){
oldCons.log(text);
//custom code here to be using the 'text' variable
//for example: var content = text;
//document.getElementById(id).innerHTML = content
},
info: function (text) {
oldCons.info(text);
//custom code here to be using the 'text' variable
},
warn: function (text) {
oldCons.warn(text);
//custom code here to be using the 'text' variable
},
error: function (text) {
oldCons.error(text);
//custom code here to be using the 'text' variable
}
};
}(window.console));
//Then redefine the old console
window.console = console;
Now, generally I would highly advise against using something like this into production and limit it to debugging purposes, but since you are trying to develop a functionality that shows the output of the console, the lines are blurry there, so I'll leave it up to you.
You could wrap the script in its own try/catch, something like:
var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow);
var head = doc.getElementsByTagName('head')[0];
var scriptElement = doc.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.text = "try{"+scripts+"}catch(e){console.error(e);alert('Found this error: ' + e +'. Check the console.')}"
head.appendChild(scriptElement);

Spying on console.error() with Jasmine

I'm actually new to JavaScript as well as Jasmine. So it might be something really obvious that fixes my problem but I can't see it.
I want to check if (an already existing) JavaScript application calls console.error() while loading. I don't really see a way how to realise this with Jasmine. I've included the JavaScript file as well as the spec file in the SpecRunner.html.
But I take it that I somehow need to "instantiate" the application in order to test if it throws any errors on the console, right?
Or should I include the SpecRunner.html code only for this purpose into the HTML code of the app?
You can spy on console.error like this:
beforeEach(function(){
spyOn(console, 'error');
})
it('should print error to console', function(){
yourApp.start();
expect(console.error).toHaveBeenCalled();
})
You can override the standard console.error function like this:
//call the error function before it is overriden
console.error( 'foo' );
//override the error function (the immediate call function pattern is used for data hiding)
console.error = (function () {
//save a reference to the original error function.
var originalConsole = console.error;
//this is the function that will be used instead of the error function
function myError () {
alert( 'Error is called. ' );
//the arguments array contains the arguments that was used when console.error() was called
originalConsole.apply( this, arguments );
}
//return the function which will be assigned to console.error
return myError;
})();
//now the alert will be shown in addition to the normal functionality of the error function
console.error( 'bar' );
This solution works with Jasmin or anything else. Just put the code above before the other codes and any call after this to console.error() will call the overridden function.
use toThow and toThrowError http://jasmine.github.io/edge/introduction#section-Spies:_and.throwError

Categories

Resources