My script dont run till the end. And stops due to errors. But there is no console error output.
alert("yo");
var go = "";
go.push(null);
alert("yo2");
first alert works
Tested with Chrome and Firefox
No try catch blocks
Are there reasons for not showing up a console error, without knowing the whole code?
You should see the error: TypeError: Object has no method 'push'
Im getting it in chrome console.
The error message is saying that the push method cannot be run on the variable go.
This is because it is of the type String and thus does have the push method available.
The push method is used to add items into an Array like this:
go = []; // or you could use `go = Array()`;
go.push("A string");
go.push(null);
To output messages to the browser console, use console.log like this:
console.log("Some debug message");
console.log(go); // outputs the above array
I solved the problem by using try-catch:
try
{
var my_app = new My_App();
}
catch(e)
{
console.log("ERROR"+e);
}
Now i get the console output.
Is it possible to get visuel notifyed if I get a Javascript error?
In developing I have Firebug or something else open so I spot it.
But in the case where I do a light demostration for someone else I can not have it open.
I still prefer to know about the error instead of it failing silently and I dont know about trailings errors where I can't distinct wish between real and trailing errors.
You can surround your code in a try-catch and call alert with the error message. For example, if your code is as follows:
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
you can surround it with the try-catch as follows:
try {
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
}
catch(err) {
alert(err.message);
}
err.message basically contains the error message, similar to the one you see in Firebug.
Edit: You may also define window.onerror. See this answer
I believe you can use try catch functionality to show the error.
Something like this:
try {var a = 20 / f;}
catch (err) {alert(err);}
http://jsfiddle.net/magwalls/h7kqr/
Hope this helps!
I am getting a javascript error "Invalid argument on Line: 2 Char: 141544 in sp.ui.rte.js" on a SharePoint development. This appears to be a known issue from google within the SharePoint js files - http://wss.boman.biz/Lists/Posts/Post.aspx?List=c0143750-7a4e-4df3-9dba-8a3651407969&ID=69
After analysing the impact I decided that rather than changing the js in the SharePoint 14 hive I want to suppress the error message for just this error. I was trying to do the following:
ClientScriptManager cs = Page.ClientScript;
//Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered("Alert"))
{
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.onerror = function (msg, url, num) {return true;} </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "Alert", cstext1.ToString());
}
The problem is this will suppress all js errors on the page not just the sp.ui.rte.js ones. Is it possible to do a string search on the URL (http://SHAREPOINT/_layouts/sp.ui.rte.js?rev=uY%2BcHuH6ine5hasQwHX1cw%3D%3D - where the only consistent value between sites will be /_layouts/sp.ui.rte.js? ) to just search and suppress this exact error?
Thanks for any help!
Use try/catch block around code in JS. If message matches something you want to ignore, just do nothing. Propagate everything else.
Your original approach with .onerror would work too if you change it to analyze message and propagate everything not matching ignored string as well.
So far this has been the most successful fix I have found and currently using:
function fixRTEBug() {
// This Fix for parentElement bug in RTE should survive Service Packs and CU's
function SubstituteRTERangeParentElement() {
var originalRTERangeParentElement = RTE.Range.prototype.parentElement;
RTE.Range.prototype.parentElement = function () {
try {
originalRTERangeParentElement();
} catch (e) { }
}
}
SubstituteRTERangeParentElement();
}
ExecuteOrDelayUntilScriptLoaded(fixRTEBug, "sp.ui.rte.js");
I have configured PHP to send me mails whenever there is an error. I would like to do the same with Javascript.
Also given the fact that this will be client side it is open to abuse.
What are good ways to get notified by mail when JS breaks in a web application?
Update:
Just to give some perspective, i usually load several js files including libraries (most of the time jQuery).
You can listen to the global onError event.
Note that you need to make sure it doesn't loop infinitely when it raises an error.
<script type="text/javascript">
var handlingError = false;
window.onerror = function() {
if(handlingError) return;
handlingError = true;
// process error
handlingError = false;
};
</script>
The code below relies on the global onError event, it does not require any external library and will work in any browser.
You should load it before any other script and make sure you have a server-side jserrorlogger.php script that picks up the error.
The code includes a very simple self-limiting mechanism: it will stop sending errors to the server after the 10th error. This comes in handy if your code gets stuck in a loop generating zillions of errors.
To avoid abuse you should include a similar self-limiting mechanism in your PHP code, for example by:
saving and updating a session variable with the error count and stop sending emails after X errors per session (while still writing them all down in your logs)
saving and updating a global variable with the errors-per-minute and stop sending emails when the threshold is exceeded
allowing only requests coming from authenticated users (applies only if your
application requires authentication)
you name it :)
Note that to better trace javascript errors you should wrap your relevant code in try/catch blocks and possibly use the printstacktrace function found here:
https://github.com/eriwen/javascript-stacktrace
<script type="text/javascript">
var globalOnError = (function() {
var logErrorCount = 0;
return function(err, url, line) {
logErrorCount++;
if (logErrorCount < 10) {
var msg = "";
if (typeof(err) === "object") {
if (err.message) {
// Extract data from webkit ErrorEvent object
url = err.filename;
line = err.lineno;
err = err.message;
} else {
// Handle strange cases where err is an object but not an ErrorEvent
buf = "";
for (var name in err) {
if (err.hasOwnProperty(name)) {
buf += name + "=" + err[name] + "&";
}
}
err = "(url encoded object): " + buf;
}
}
msg = "Unhandled exception ["+err+"] at line ["+line+"] url ["+url+"]";
var sc = document.createElement('script'); sc.type = 'text/javascript';
sc.src = 'jserrorlogger.php?msg='+encodeURIComponent(msg.substring(0, Math.min(800, msg.length)));
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s);
}
return false;
}
})();
window.onerror = globalOnError;
</script>
You would wrap your entire program in a try/catch and send caught exceptions over AJAX to the server where an email could be generated. Short of that (and I wouldn't do that) the answer is "not really."
JA Auide has the basic idea. You could also go somewhat in between, ie.:
Write an AJAX "errorNotify" function that sends error details to the server so that they can be emailed to you.
Wrap certain parts of your code (the chunks you expect might someday have issues) with a try/catch which invokes errorNotify in the catch block.
If you were truly concerned about having 0 errors whatsoever, you'd then be stuff with try/catching your whole app, but I think just try/catching the key blocks will give you 80% of the value for 20% of the effort.
Just a note from a person that logs JavaScript errors.
The info that comes from window.onerror is very generic. Makes debugging hard and you have no idea what caused it.
User's plugins can also cause the issue. A very common one in certain Firebug versions was toString().
You want to make sure that you do not flood your server with calls, limit the amount of errors that can be sent page per page load.
Make sure to log page url with the error call, grab any other information you can too to make your life easier to debug.
How can I print a message to the error console, preferably including a variable?
For example, something like:
print('x=%d', x);
Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).
console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.
You also can add CSS:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
More info can be found here: https://developer.mozilla.org/en-US/docs/Web/API/console
Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Usage:
log('Hello World');
log('another message');
One good way to do this that works cross-browser is outlined in Debugging JavaScript: Throw Away Your Alerts!.
Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)
As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.
The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.
It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.
Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.
If you use Safari, you can write
console.log("your message here");
and it appears right on the console of the browser.
To actually answer the question:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Instead of error, you can also use info, log or warn.
If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.
The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).
A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)
My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...
As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().
jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}
Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference
console.error(object[Obj,....])\
In this case, object would be your error string
function foo() {
function bar() {
console.trace("Tracing is Done here");
}
bar();
}
foo();
console.log(console); //to print console object
console.clear('console.clear'); //to clear console
console.log('console.log'); //to print log message
console.info('console.info'); //to print log message
console.debug('console.debug'); //to debug message
console.warn('console.warn'); //to print Warning
console.error('console.error'); //to print Error
console.table(["car", "fruits", "color"]);//to print data in table structure
console.assert('console.assert'); //to print Error
console.dir({"name":"test"});//to print object
console.dirxml({"name":"test"});//to print object as xml formate
To Print Error:- console.error('x=%d', x);
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
console.log("your message here");
working for me.. i'm searching for this.. i used Firefox.
here is my Script.
$('document').ready(function() {
console.log('all images are loaded');
});
works in Firefox and Chrome.
The simplest way to do this is:
console.warn("Text to print on console");
To answer your question you can use ES6 features,
var var=10;
console.log(`var=${var}`);
This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:
just do:
alert("message");
With es6 syntax you can use:
console.log(`x = ${x}`);