Improving our javascript error reporting - javascript

So right now we have some generic code to report errors either from our code or third party code. Our project is a JQM/Phonegap project for iOS. What is happening is we pretty much always get the same useless error... TypeError: 'undefined' is not a function... with no line number or other helpful information. Is there a way I could change the code to maybe get WHAT is undefined or WHERE it is?
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
//Handle errors not in a jquery event handler
//DebugMessage(errorMSg + " "+ url + " " + lineNumber);
var ex = new Error(errorMsg, url, lineNumber);
HandleError(ex, "window.onerror");
//HandleError sends the error object to
//a webservice to log the error.
return true;
};
Any tips on debugging javascript errors would help as well.

In recent months, browsers have extended the signature of window.onerror to provide more information.
window.onerror = function(msg, file, line, col, error) {
// backwards compat
if (!error) {
error = new Error(msg);
}
// send error to your logger
}
This should give you a lot more information. But there are still things where you need better context. You should check out some third-party tools for this like TrackJS that automatically give you this, plus extra information on how the error occurred.
Disclaimer: I am one of the original authors of TrackJS, so I know a bunch about JavaScript errors :)

Have you heard of Ripple? It is a mobile emulator for Chrome designed for testing PhoneGap applications.
That might help you find your errors before you debug on the devices.

Related

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}

new google script version throwing javascript error

I have a Google Script-JSON-javascript webapp working but when I changed the JSON output, saved a new Google Script version, and published as web app, the webpage throws a CORB error.
Going back a version in GS, allowed it to work again. Why would a new GS version cause an error. Even with the same code but in a new version the error is still thrown. Is there a GS version caching issue? What I can do to update the version?
Working page with current version: https://arcacademy.ca/arc-academy-calendar-2018-2019/
Note: You can see in Console the JSON text being sent. The new code has the same format/structure, except changed the color values from hex to 1 to 10.
To tried to fix this by creating a new GS script but receive the same error:
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://script.google.com/macros/s/AKfycbyM51kxwQOYM3hRyrW7semhmUka2z2w-jU09KBPL38IxKapeQQ1/exec?callback=receivedCalendarEvents
with MIME type text/html. See
https://www.chromestatus.com/feature/5629709824032768 for more
details.
Here's the not working page throwing above error in console: https://arcacademy.ca/clone-of-arc-academy-calendar-2018-2019/
Google Script web app deployed with:
Execute as Me
Anyone, even Anonymous
Google Script code:
function doGet(e) {
if (e.parameter.method=="populate_events") {
var scriptProperties = PropertiesService.getScriptProperties();
var calendarId = scriptProperties.getProperty('calendarId') || 'primary';
var v = extractCalendarDateColors( calendarId, e.year );
return ContentService.createTextOutput(e.parameter.callback + "(" + JSON.stringify(v) + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
}
Javascript code for working page (src= is the only thing changed for error page):
<script>
calendarEvents = {};
function receivedCalendarEvents(jsonData) {
console.log('received',jsonData);
calendarEvents = JSON.parse(jsonData);
}
</script>
<script src="https://script.google.com/macros/s/AKfycbzMCDiTzxGx2cN5dtXqCG2gvxJ6FGZ_t6UuPiT-HyDesu2--EY/exec?callback=receivedCalendarEvents"></script>
<script>
Google Console Cloud -- I have set the following:
Enabled Calendar API
Added Apps Script Client ID
I feel like I'm lost in Google access land. Any help would be greatly appreciated!
Thank you Tanaike for the inspiration on this problem. The CORB (cross origin error) was, as you mentioned above, likely to do with javascript call.
I updated the javascript: https://script.google.com/macros/s/#####/exec?method=populate_events&year=2018
And updated the google script to use the parameters without throwing an error:
e.parameter.method
e.parameter.year
So it seems all the time I was getting the cross origin error, it was from a poorly formed javascript call and an error on the google script side, which returned an error and not a properly formed JSONP object.
Thank you for your help Tanaike!! :)

How to catch all javascript warnings and errors to an output div?

i'm using try, catch, for debugging, but warnings is not create exceptions. How to get all javascript warnings and errors to output div?
UPDATED:
If browser supports Afaik logging, how to get that log to string or output div?
UPDATED:
I found the way how to do that:
i can reload console.log function to my custom function an call native console.log function.
First of all, get rid of the try catch. Don't use try catch when you are debugging.
Second, you don't want to out errors to a div, use firebug or inspector for that - console.log();
Third, if you really want to do it: you could use try catch and in the catch, use something like
$('body').append($('div').html('variable for error message goes here'));
if you are using jquery
OR
document.getElementByTagName("body").appendChild( document.createTextNode("variable for error message goes here") );
if you have plain javascript
EDIT: try looking up ie debug bar , ie webDeveloper
I understand myself why someone may want something to actually happen when an error occours in the document. The answers above just say that you would use developer tools, but I needed things to actually happen, and after some searching, here's what I found...
If you wish to catch all errors that come through, you can put the following code into your file, best at the top:
window.onerror = function(errorMsg, url, lineNumber){
// any action you want goes here
// errorMsg is the error message itself.
// url should be the file presenting the error, though i have
// found that it only presents to me the address of the site.
// lineNumber is the line number the error occoured on.
// here is an example of what you could do with it:
alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}
I, myself, like to output the errors to a div that contains them all, though you can do literally anything to this information that you could do with any other string passed to a function.
Here is an example of what may happen if you throw an error with a button using the code above:
Error in your.site.here at 1:
Uncaught ReferenceError: foo is not defined
For IE javascript debugging you can follow this guide:
http://msdn.microsoft.com/en-au/library/ie/gg699336(v=vs.85).aspx
Keep in mind that the developer tools window must be open prior to loading the page for the warnings and errors to appear in the console.
For webkit, (chrome, safari) developer console - here is a guide:
https://developers.google.com/chrome-developer-tools/docs/console
...Firefox also has a console

Is there a way to try/catch an entire page dynamically?

I have a page on which mysterious JavaScript errors keep popping up. They appear to be coming from the application we use and do not own the source for. I'm working on a real solution to this issue, but we have a demo tomorrow and I was wondering if there is a way to just suppress JS errors page wide (like wrapping ALL the javascript components in a giant try catch).
You could add a handler to the window.onerror event. In this case, all the errors that occur inside the window will be redirected to the handler of this event. (I did test this in Firefox and it worked, but I was having trouble with it in Chrome - my Chrome installation is pretty messed up, so that could be the problem, but there are Chromium bugs filed that relate to this issue: bug #7771 and bug #8939)
window.onerror = function (msg, url, line) {
alert("Error on line " + line + " in " + url + ":\n" + msg);
// return true to prevent browser from displaying error
return true;
}

Firebug not showing Javascript errors for Rails applications

I have a Rails application, and when I have Javascript errors they are not showing in the Firebug console. I have 'Show javascript errors' and 'Show javascript warnings' selected.
When I insert javascript errors in a basic html file, the errors show as expected.
In the javascript of the Rails app, it only shows errors in rare cases.
For example i can insert nonsense like:
dfghaefb;
and no error is shown in Firebug. But if i insert a space in there Firebug does show the error:
dfgh aefb;
Any ideas? This is driving me nuts.
UPDATE:
Pumbaa80 was right, it's syntax vs runtime.
So I set up onerror:
onerror=errorHandler;
var error="";
function errorHandler(errMessage,url,line){
error="There is an error at this page.\n";
error+="Error: " + errMessage+ "\n";
error+="URL: " + url + "\n";
error+="Line: " + line + "\n\n";
error+="Click OK to continue viewing this page,\n";
alert(error);
return true;
}
And I have a method with an error:
function initForm() {
asdfs;
}
And it works when I call it outside of a method:
initForm();
but not in this case:
document.observe('dom:loaded', function() {
initForm();
});
Why is that?
dfghaefb;
produces a run-time error. Those errors may be suppressed by putting an onerror handler on the window or by trapping them in a try/catch in some way. In that case, Firebug won't show anything.
In contrast,
dfgh aefb;
is a syntax error, which is shown in the error console, regardless of try/catch and onerror.
Did you let the page load completely? I have a rails app running in front of me right now with firebug on and i entered dfghaefb; and yes it does throw an error!
ReferenceError: dfghaefb is not defined { message="dfghaefb is not defined", more...}
Running Firefox 3.6.3, Firebug 1.5.3 and MacOSX 10.5.6 :)
This may appear to be obvious, but be sure you wrap your inline JS using
<script type="text/javascript"> code </script>
Otherwise FireBug won't look at it at all.
I had the same, it wasn't showing anything and it was driving me crazy for ages, even if i had "Show javascript errors" in the console tab selected, it seems that it started working after I did "Enable all panels".
These kinds of problems cannot be answered without a test case.

Categories

Resources