I want to see the warnings in order to do a better debugging of my application which is made in Asp.Net, so it has a lot of code generated in javascript. The problem is that pages reload fast and I can't take a look at the warning messages. I want to know if there is a way to break on warnings in Google Chrome, as in this question is described how to break on errors. Is there a way to do this, or what alternatives do I have?
As #Nitsew has already said, preserving the log is a great solution. But just for fun, and because I thought your question was interesting, I decided to work out a solution to do what you asked; cause a debug to occur when warn is used:
function testBreak() {
console.warn('This is a warning', 1, 2);
return 1;
}
var oldWarningFunction = console.warn;
console.warn = function () {
debugger;
oldWarningFunction.apply(console, arguments);
};
console.log(testBreak());
Essentially, I have monkey-patched the original console.warn to output a debugger statement. When this causes the debug to occur, you will probably need to view the stack trace to see where you were in the code:
Once you click back one on that stack trace, you can see the function that made the call.
This all seems rather silly since you could just write your own debugger statement right in your code where you want them. And one other thing, to whoever may read this and tries it: Do not leave this in your production code
If you are just trying to look at the console messages, turning on "Preserve log" might be an easier solution.
Related
I am starting to learn EmberJS/JS/VIM . I was going through the official ToDoMVC guide for EmberJS, and I ran into typos errors that was really really hard to detect with the "eyes" and the browser really didn't help in this case at all. So, can you please suggest me what tools or techniques that can be used to detect these types of typos errors?
For example:
### todo_controller should've been todos_controller
<script src="js/todo_controller.js"></script>
### catching the end of { } closed scoping
### typo within a model js "property"
inflection: function() {
var remaining = this.get('remaining');
return remaining === 1 ? 'todo' : 'todos';
}.proprety('remaining')
EDIT;
Yes, I did search before posting here. The first was this website, and the comments here basically suggest DreamWeaver Frustration with Typos.
I searched SO itself (through google), and there was Is there a way to catch typos. I did find out there is something called LINT, but it dealt with coffeescript.
I did find out ember.vim as you pointed out before, but as you see the README in the github profile, i believe it strictly wants you to follow the layout as prescribed. It may be a good thing in future, but right now, I wanted to just stick with what the official ToDoMVC way. I am just beginning to get a hang of hjkl, so I do not think I can makes changes to it to fit my way. Also, second point, is the layout format it supports is Ember-AppKit which has been deprecated. SO I am having doubts if I should follow the layout pattern itself.
And all of them didn't particularly address what I am asking. In the todo_controller typo above, the browser didn't throw any sort of errors. I am using FF/Firebug, and on the Console, it only showed the message about Ember loading, and no errors at all. It took me a while to see that typo. The second one did throw errors, but typos are a hard thing to discover in VIM. The third one, took a bit of time, and there were others. These don't throw errors at all. I am used to PHP, and while there is no direct showing of errors as in Android, I am finding Javascript typo hunting to be very hard.
it took me like 3 looks before I saw your typo.
Set your browser to pause on exceptions (sometimes pause on Caught Exceptions). It's been one of the quickest ways I've found to track down a weird bug. In this case I'm sure you were getting Uncaught TypeError: undefined is not a function....
Don't take this the wrong way, but did you try to search before asking? There has been, for quite a while now, a plugin for Vim that has syntax highlighting improvements.
https://github.com/dsawardekar/ember.vim
Beyond that plugin, you could try writing your own solution. I haven't tried, but I doubt there is anything out there that will pick up spelling errors for Ember...
I use JSLint for SublimeText 3, which lints as you code so you get a live update of any potential bugs. Kinda nice. Here's something similar for Vim: https://github.com/hallettj/jslint.vim
As #kingpin2k suggests, you should really learn how to use your browser tools. The big three are just jam-packed full with development and debug tools. 9 times out of 10 it gives you the line and column of the error, and you can set breakpoints within the code to watch it execute in-context. And, that is really just the tip of the iceberg in terms of how detailed you can get with debugging in-browser.
I'm truly stumped by this problem.
I've got some JavaScript to control a product configurator.
A simple bit of code to select some defaults
works fine in Chrome
works fine in IE
doesn't work in Firefox (newest versions of everything)
However, if I do anything to observe the code in FF it works fine.
If I have it alert anything relevant, it works.
If I log anything relevant, it works, but only if the console is actually open so I can see the log. If the console isn't open, doesn't work.
for(type in radio_groups) {
if_checked = !!$(":radio[name="+type+"]:checked").length;
console.log($('.'+type).not('[class*="unavailable"]'));
//This loop doesnt do anything without this log above
alert($('.'+type).not('[class*="unavailable"]'));
// Or this alert.
var t = $('.'+type).not('[class*="unavailable"]');
// Line above doesn't make stuff work.
if(!if_checked)
$('.'+type).not('[class*="unavailable"]').first().click();
}
if_checked is false for every type, I can verify that when it runs.
However, nothing happens.
No buttons are clicked.
This is plain single threaded JS in a browser.
There's no interval/timeout functions on the page.
I can do time arbitrary time consuming tasks before the last line (my best idea was that it was a concurrency issue somehow, I don't see how else logging could affect anything) and it doesn't have any effect.
I can run the same selector and put it in a string, or do anything you can think of to it besides logging or alerting and it wont work; no buttons get clicked. Only actively observing whats happening makes the code work. The entire deal is rather involved and I cant provide the entire thing.
Any ideas on how:
logging can possibly affect the outcome of a simple click event?
why this is Firefox specific? Or other ways I might try to see whats going wrong without the console or alerts?
Edit: Oh, and I've had two other people replicate the issue in their browsers (again, Firefox only), so its not some wonky extension issue unless we all share it.
Thanks.
This line is not valid:
var t = "$('.'+type).not('[class*="unavailable"]')";
It should probably be:
var t = "$('.'+type).not('[class*=\"unavailable\"]')";
or:
var t = $('.'+type).not('[class*="unavailable"]');
Here's a bit of speculation:
if_checked = !!$(":radio[name="+type+"]:checked").length;
It looks like the quotes aren't paired correctly. Did you mean this?
if_checked = !!$(":radio[name='"+type+"']:checked").length;
(See the single quotes that wrap the value of type?)
I've come across this before. If I'm leaving any logging in place in production code I'd wrap it in a try > catch statement.
try {
console.log("my log message")
} catch (err) { };
I know it's considered bad practice to have an empty 'catch' but hey, it's also bad practice to leave the logging in on priduction code.
It seems in FF (also in older IE) if the console is not open then it doesn't exist so the error being caught is probably something like 'console is undefined'
I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.
Can someone explain why the console acts this way?
I posted this question once, but I could not quite formulate it correctly so I closed it again. The initial question did not mention that the problem could be console related, I just questioned the strange behavior of the variables. I basically only posted the following screenshot:
Note here that I log $s.page on line 20 and $s.page.navi is there, and on line 21 when I log again it's gone.
Reopening the question
There was nobody who could give an answer, although #zerkms suggested it could have something to do with the console itself. After I closed the question he contacted me via this post: Have require.js load my files only when I actually need them to maybe reopen the question.
The Problem
Enough intro, back to the issue. So where did the variable go. From the other question I posted you can see I use require.js to load my files. I am kinda new to this all so my problem was related to it.
In the code of $s.page I do the following (simplified):
require(['nav'], $.proxy(function(Nav){
this.navi = new Nav.Views.Main();
}, this));
nav is a module that require.js has to load. I the script would block until the file is there, and looking at the console it confirmed that.
Let me log in more detail:
console.log('x');
require(['nav'], $.proxy(function(Nav){
console.log('y');
this.navi = new Nav.Views.Main();
}, this));
I left the other logs in place aswel, and here is the output:
Notice that x is logged first. When I then log $s.page it shows me what $s.page will look like in the future, i guess. Really odd.
When I then log $s.page.navi on the next line it is not there, which is correct.
Then at the very end, without even being called anymore, y joins the party.
See on line 22 of router.js I call $s.page.navi.start(), that was the whole point of this problem. It could not be fired. I solved it with the following code:
require(['nav'], function(Nav){
$s.page.navi.start();
});
It will just wait for it's dependencies.
Conclusion
When working with JavaScript, and libraries such as backbone.js and require.js you should really keep track of what you are doing and keep in mind that the script does not easily block.
Just logging at certain points in the application will not always help you solve your problem, you have to really log from the root of your application to the tip of the leaf to see what is actually happening. And the best approach is always the build in debugger.
I'm working on a new project which has some complex javascript. I can't post any code so that's not what my question is about.
I have a script which works in Firefox 3.0. It was pointed out that the script did not work in Firefox 3.5, so I'm trying to make it work. Indeed the script didn't produce the expected results, so I installed the latest version of Firebug, enabled the console and refreshed the page.
And wow, it worked.
No errors, warnings nothing.
So I disabled the console, and then it didn't work anymore...
What's going on here? The Firebug console somehow changes something in Firefox that makes my script work? Any advice on what next? (besides asking future visitors to install Firebug...)
Could it be something as simple as forgetting to comment a call to console.log() somewhere in your javascript?
If you have hanging references, and the user doesn't have Firebug installed, you're going to get a runtime error that will halt execution of the script.
It sounds to me like there's a chance you have a threading problem, and FireBug is analyzing and possibly slowing down one of the threads so that it has time to complete before the next step is resolved.
Are you possibly utilizing ajax, and something is waiting on that response? Or possibly you're doing something on or after the load of an object that is depending on something else in the DOM?
UPDATE:
For those stumbling upon this now, "threads" in JavaScript really only exist in abstraction (web workers, etc). I was mis-using the term. I was really thinking of an asynchronous action that returned before another one was ready.
Check in your code for console.log(), console.debug().Calling window.console objects methods throws an error if console is undefined (as expected).
In most cases you can easily delete or comment that lines.
I wrote a simple wrapper for firebug (I just use debug but it should give you what you need to duplicate the other methods) that only writes when the console is there so I can use firebug, don't need to go comment out my debug statements and it doesn't break sites for people without it.
If you use this code then use fbconsole.debug instead of console.debug you will never have this problem:
function fbconsole () {
this.debug = function (val) {
if(typeof(console) !== 'undefined' && console != null) {
console.debug(val);
}
}
}
var fbconsole = new fbconsole();