What's the best way to debug Javascript/AngularJS? - javascript

I just started learning Javascript and AngularJS and have a decent Java and C++ background.
Today I wasted an entire day debugging a trivial error that boiled down to a missing comma in a JSON file: "name": "Melbourne",
"snippet": "Melbourne"
"location":{"lat": "37.8136S", "long": "144.9631E"}
Now I'm wondering:
What's the Javascript/AngularJS way of debugging? - for this specific case as well as in general. Spending 8 hours changing every line in the code can't be the solution.
In C++/Java I would look at the stacktrace so i checked the chrome console output and found:
SyntaxError: Unexpected string
at Object.parse (native)
at fromJson (http://localhost:8000/app/bower_components/angular/angular.js:1078:14)
at $HttpProvider.defaults.defaults.transformResponse (http://localhost:8000/app/bower_components/angular/angular.js:7317:18)
at http://localhost:8000/app/bower_components/angular/angular.js:7292:12
at Array.forEach (native)
at forEach (http://localhost:8000/app/bower_components/angular/angular.js:323:11)
at transformData (http://localhost:8000/app/bower_components/angular/angular.js:7291:3)
at transformResponse (http://localhost:8000/app/bower_components/angular/angular.js:7963:17)
at wrappedCallback (http://localhost:8000/app/bower_components/angular/angular.js:11319:81)
at http://localhost:8000/app/bower_components/angular/angular.js:11405:26 angular.js:9778
How is this supposed to help me? I see nothing that even remotely tells me to check my JSON or my code - only library code. The offending lines in my code are
//citycontroller.js
$scope.cities= City.query();
//cityservice.js
cityServices.factory('City', ['$resource',
function($resource){
return $resource('cities/:cityId.json', {}, {
query: {method:'GET', params:{cityId:'cities'}, isArray:true}
});
}]);
Why isn't there a stacktrace for either of these lines?

I spent most of yesterday dealing with nearly the same issue.
A lot of the Angular error messages will actually provide a link that you can click on and it'll take you to an Angular page that provides a more detailed error message.
This feature doesn't seem to have made it to the parser, yet.
The stacktrace probably should include a reference to your code but maybe it's too far down or maybe it didn't make it in there because the problem isn't with your code, it's the library the blew up.
My clues in these error messages come from the first few lines:
"Unexpected string" = I'm getting a string when I don't expect one
"at Object.parse (native)" = I was trying to parse through some data
"at fromJson" = I was parsing JSON data when I crashed
My error was nearly the same but I got "Unexpected token ," which means that it found a comma where it didn't expect one.
As for other Angular debugging practices, my code lives and dies by the Chrome (or other browser) console.
Console.log is one of my code's best friends. In this case, it probably would have helped you because it wouldn't have been able to properly render the malformed JSON in the console. When in doubt, log it out!
I also use the Chrome console to see the exact request that was sent to the server. Often, you can double click that request and open it in a new tab so that you can make the same request repeatedly. This gives you the opportunity to see how the response changes as you change the server-side code.
Good luck.

Why isn't there a stacktrace for either of these lines?
Because the operation is async,and doesnt happen on the "same" stack as your code.When the ajax call returns,the stack in your code has already been "unstacked" a long time ago.
A good explaination of what's happening can be seen here :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
There is basically,a stack,a heap like other languages, but also a queue of async operations that will have their own stack.
That's why for instance,if you throw an error in a async operation(a setTimeout for instance),you cant try/catch it in the stack that triggered the setTimeout.
The rest is experience.You need to learn that Object.parse (native) refers to JSON.parse.You also need to learn AngularJS api,obviously angular.fromJson method is related to a (de)serialization operation.

You can set your breakpoints in chrome(hit f12 to open up dev tools). Then you can step through your code line by line to see if you missed anything. Also you might want to look up Batarang which is a chrome extension used to specifically debug AngularJS.

Use IDE application to inspect the code for syntax error.
If your application retrieves data from JSON file, use JSON validator to check those json file.

Related

HOW TO RESOLVE: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This error occurs in Firefox console when loading 3rd party Javascript. But Firefox console gives absolutely no information as to whereabouts in the JS this issue occurs. The 3rd Party JS has a host of different JSON parts to it.
I am not familiar enough with JS to dig in and mess around with the code toooo much or spend hours fragmenting it and taking it apart and putting it back together again.
NOTE
There are a lot of questions with identical titles, and each of these show very specific issues with very specific responses. My question is not really about wanting to find the issue in this case (although that would be great).
My Question
How should I (any anyone else) approach trying to find where this error is;
How do we find what data is causing this error?
How do we find which line of JS causes this error?
Reading the MDN (etc) on JSON errors It seems to be easy to resolve once it's been found, but the case is I am having troubles finding how to go abouts digging out where in the JS this issue occurs and/or which data is causing the JSON error.
UPDATE
Further to comments, here is the Debug flow output from Firefox; I'm a little lost in here but this still doesn't seemt to show me what is actually going on.
Some clear pointers that came up in the comments below the question:
Use the Debugger Firefox Inspector tab before refreshing the page and reloading the error.
Somewhat unexpectedly, when on the Debugger tab, the same console error (at the bottom of my screenshot) this time shows a file reference and line number reference and can be clicked on to show a cascade of details.
As mentioned by evolutionxbox and Barmar the Debugger tab should also be showing the variable that's used in the call to JSON.parse.
Using the Debugger Breakpoints tickboxes was very useful for establishing what part of what code was running when the error was encountered.
More will be added here

Debugging JavaScript in client

I'm facing an issue while debugging my application. Following is the architecture:
Server: Java (Servlet)
Client: React+D3
Problem: Whenever, I change some react or d3 code and if an error occurs then it just shows me that some react (or d3) error has occurred but never tells me which function the error occurred (as seen in snapshot). Now, I know that simply debugging it by having the information like variable name and searching where I defined that variable. However, situation becomes tough when I use same object multiple times (say window) and had made several changes in the code. In this case, a specific line number where the error occured can be handy and quick. Let me know if I'm missing some basics about debugging such applications?
EDIT1:
1. In the snapshot, http://localhost:8080/..../Server Server is the main servlet application, kind of launchpad, which triggers several other react-based js files.
2. The mentioned ReferenceError is inside a function updateWindow() but the console never mentions this (and that's my problem).
PS: I'm using Eclipse tomcat on server-side
I think there's no straight forward solution to this problem. So, I'll post the method that worked for me with few additional points:
Problem: It doesn't gives a nice error trace like standard Java application, probably because it mixes with JavaScript code.
At every line of the error trace, line:column specifies the error line. I used this as a reference and started manual debugging from where my application launches i.e. Server.java and look where I defined the createChart() in the JS file and drill-down until I found the referenced variable.
In case of ReactJS' error (an error after resolving reference issue), I debugged it with normal react.js (not minified version react.min.js) so that it shows me exact line of error. Minified version is cluttered and is useless while debugging.
PS: If someone has better answer I'll edit this in future.

Debugging Ember JS -- Identifying line in code that causes an error

So I'm getting the following error:
Uncaught Error: Assertion Failed: The key provided to get must be a string, you passed undefined
Should be easy enough to fix, if there was any indication of the line in my code that causes that error.
Using the chrome console, I click on ember.debug.js:6254 next to the error, which just shows me the ember code that throws the error. I can expand the error, but I just get a bunch of functions that can't be clicked on and no indication where they come from.
Can someone please help me figure out how to identify the line in my Ember code that is causing the error.
I've gotten this error before. It happens when you call get() in any of its forms (Ember.get() or this.get() or get(this)) without a string as the name of the property you want to retrieve.
You should be able to find the source of the error by auditing your application for wherever you call get() and making sure you pass the property name as a string. E.g., Ember.get('model.someProp') or this.get('someProp') or get(this, 'someProp').
This should be a comment but I can't, so here goes:
Iam new to Ember and have been spending quite a long time debugging. Remember that long stack of function calls that chrome's console shows.
Look for anything other than ember.debug.js...especially those marked (anonymous function) and files with names vendor.js or app-name.js
Usually in software development when debugging your best friends are going to be console.log() or alert() (in the case of JavaScript). Usually you have to figure out if your getting what ever is that you passing to your function by consolelog everything until you find your bug. Ember sometimes will not tell you what is exactly the error because does not know where exactly is coming from.
...computers are annoying but we love them....
here are some articles from Mozilla developer and Google on how to debug JavaScript.
I had a NULL value in my database which I wasn't accounting for in my app. In my case, it shouldn't have been NULL in the first place, so after giving the record a value in my database the problem disappeared.
I agree the error message is not very helpful.

Solving a mootools error / conflict using Gantry Framework on J3.0.2

I am having problems finding the solution to two errors on a web site I am building on a Joomla 3.0.2 platform and using the Gantry Framework.
The first error is:
Type issue
'null' is not an object (evaluating 'b.appendChild')
The second error is:
Type issue
'undefined' is not an object (evaluating 'rikgallery_slideshow.jump')
I have never understood how to debug javascript errors, so I would really appreciate some help.
The site can be accessed at: http://lads.ergonomiq.net
If someone can help and needs super user access to the back end, please email me at ali.samii#ergonomiq.net
Thanks
This is meant to simply point you in the right direction, further testing will be required to fully solve your issues.
OK the first error is happening in responsive.js line 66
menu.inject(document.getElement('.menu-block'));
I would console.log(menu, document.getElement('.menu-block')) make sure both contain an element as expected. I am guessing one of those will be null.
Second error
AjaxURL: 'http://lads.ergonomiq.net//index.php?option=com_roksprocket&task=ajax&format=raw&ItemId=101'
is returning unexpected JSON
{"status":"error","message":"Unable to find class for item ","payload":null}
I would test the error and only proceed if you have images in your returned JSON
Line 136 of your home page.
Hope this helps
I have never understood how to debug javascript errors, so I would
really appreciate some help.
If you want to debug JavaScript errors, you should be using FireBug with the FireFox browser. You can get the FireBug Add-on here. You will then be able to find these bugs yourself.

Output the rendered contents of a page on a JavaScript error

I'm having problems with getting decent JavaScript error invormation in a Production environment.
When I'm developing I can just attach a debugger and (usually) fix the problem.
When I get the same error in a production environment however at best I see is an error report that looks like this:
Error: Object doesn't support this property or method
Url: SomePage
Line: 42
Char: 13
Which doesn't help me very much - I can't see the rendered page and so I have no idea what line 42 looks like.
Is there any way for me to log the entire rendered page contents whenever an error like this occurs? (So line 42 of the output is the line where the error occured)
While I'm at it, are there any other techniques that I can use to help with getting useful error information from JavaScript (without need to break into the debugger) - failing that is there any way that I can structure my JavaScript slightly differently to help getting decent debug information?
I'm predominantly interested in IE - this is the browser that tends to cause me most problems.
I don't think you'll be able to get the exact original HTML source of the page back in all pages and all browsers.
Regarding debugging, you could use a logging library such as log4javascript (disclaimer: I wrote it) and intersperse logging calls in your code. log4javascript enables you to send logging messages back to the server via Ajax.
Unfortunately, IE has by default the most utterly useless error reporting. The script and line number reported in the error are essentially guaranteed to be absolutely wrong. You can, however, install the IE developer tool bar (for IE7 and older, it's built into IE8) from Microsoft, which can help track down the error source.

Categories