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.
Related
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.
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
In JavaScript, when using a try catch, how can I get the native Chrome ReferenceError object to the console as it would normally be logged? I can get close by using the Error object's stack property, but it logs the errors differently:
try {
bet you can't run this you dumb computer;
}
catch(error) {
console.log(error.stack);
}
When running the above, I get the following in the console:
While this is slightly helpful, clicking on the line number takes me to the console.log(error.stack) line in the code, not the error.
Without the try catch, the error looks like this:
and clicking on the line number will take me exactly to where the original error occurred. So how can I get this native Chrome error object to pass to the catch and then log to the console so that I can navigate to the original error and line that was thrown as it would normally be without the try catch in place?
I believe it'll work with the error method from the console object:
try {
bet you can not run this you dumb computer;
}
catch(error) {
console.error(error);
}
Hope this helps!
I'm working on an existing project, with a lot of webpages. My task is to introduce logging og client script errors, usingsentr/raven-js.
In the docs, it says that i need to wrap the functions that I need to track in try/catch blocks - this is familiar to me, since I usually work in C#. But I don't wat to edit alle pages to wrap ALL javascript functions in try/catch. Is there a way to log ALL errors?
I tried something with window.onError = Raven.process, but I didn't get any logentries.
Can someone show me a what I'm missing? My setup is this:
var options = {
logger: 'my-test-logger',
whitelistUrls: [
/localhost/,
/localhost:2109/
]
};
Raven.config('https://<public-key-removed>#app.getsentry.com/<project-key-removed>', options).install();
window.onerror = Raven.process;
My setup was correct, except for the line:
window.onerror = Raven.process
For some reason I couldn't provoke any error to fire the logging event, but once I managed to simulate a real error, the logging worked just fine. The line:
Raven.config('https://#app.getsentry.com/', options).install();
does catch all errors.
It is important to realize that raven does not capture errors you trigger with the console. You need to put some error generating code directly in the page, or do something like this from the console:
window.setTimeout(function(){ foo() });
Also, i think that doing:
window.onerror = Raven.process
Is unnecessary, Raven already does that for you, in a much more advanced way.
Try the following code to disable logs from raven.js
Raven.config('your dsn', {
autoBreadcrumbs: {
console: false
}
});
Raven will from version 1 log all window.onerror errors by default.
See https://raven-js.readthedocs.org/en/latest/config/index.html#collectwindowerrors
UPDATE
[Rewriting question to focus on the problem I am trying to understand.]
Is there a means in JavaScript to throw Exceptions that notify the line number where the problem occurs? Similar to C#'s debugger, if an error is thrown on line 50 then I will be taken to line 50.
For example, according to MDN EvalError represents an error with eval(). So, let's say I have a function that uses eval(). I want to use a specific error that is representative of the problem at hand, EvalError:
//As written here the error implies there is a problem on this line. See Firebug console window
var evalErra = new EvalError('required element missing from evaluation');
var stringFunc = "a=2;y=3;document.write(x*y);";
EvalString(stringFunc);
function EvalString(stringObject) {
//Some arbitrary check, for arguments sake let's say checking for 'x' makes this eval() valid.
if(stringObject.indexOf('x') !== -1) {
throw evalErra;
//throw 'required element missing from evaluation';//This way offers no line number
}
eval(stringFunc);//The problem really lies in the context of this function.
}
If I'm going about this all wrong, then please tell me how I should approach these kinds of issues.
When you throw an error, execution of the current code will stop and JS will work its way back up the execution tree until it finds a catch () which handles the particular type of error being thrown, or gets all the way up to the top of the tree, causing an "unhandled exception" error: You threw an error, and nothing caught it, and now someone's window got broken.
try {
if (true) {
throw 'yup'
}
} catch (e) { // catches all errors
... handle the error
}
When doing error handling you want to do the following
throw new Error("message");
Then if you ever handle this error look at err.stack (firefox/opera/chrome) or err.line (Safari) or err.IE_Y_U_NO_SHOW_ME_ERROR_LINE_NUMBER (IE) to find the line number.
If you want you can subclass Error.