I'm having a bit of fun on https://blockly-games.appspot.com and have got to the last level where you can write full blown javascript (new Date().getTime(); is very handy).
Despite having the console open in Chrome (ctrl-shift-j) I can't seem to write anything to it with console.log("test"); from within the game. When I do I see:
// Starting battle with 2 players. compressed.js:420
// [Player] throws an error: Unknown identifier: console compressed.js:423
// undefined compressed.js:423
// [Player] dies. compressed.js:416
Yet if I type console.log("hmm"); in the console I properly see:
// console.log("hmm");
// hmm VM1038:2
// undefined
Same story if I try to use alert("test").
I want to debug, but the only forms of output I've found are manipulating the duck and throwing Unknown identifiers. Is there any way out of this sandbox?
Update: How do I print debug messages in the Google Chrome JavaScript Console? has some ideas for restoring console but they don't seem to work in this case.
Update: just to be clear this is what chrome looks like when experiencing this error.
Found a kludgey workaround:
throw "\nYour message here.";
Displays:
// [Player] throws an error: Unknown identifier: compressed.js:423
// Your message here.
// undefined compressed.js:423
// [Player] dies. compressed.js:416
Killing yourself just to log something may seem harsh but now you can write some snazzy asserts.
function assertTrue(test, message) {
if (!test) {
throw message;
}
}
It works, but Lord knows I wish there was a better way.
Related
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 );
}
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
I am receiving an error in my error console which states: arguments array passed to Function.prototype.apply is too large and the file it is in is: resource://ct2504091/BackStage.jsm. Does anyone know why this error suddenly appears out of the complete blue?
Below is the code from the view source of where the error is appearing in:
var postBytes = stream.readByteArray(stream.available());
poststr = String.fromCharCode.apply(null, postBytes);
A Google search for "javascript BackStage.jsm" reveals: You seem to have installed a "Bibirmer for Firefox Plugin" that interfers with you code. Try uninstalling it.
I get the following error and iPad but not in desktop browsers:
JavaScript: Error
undefined
TypeError: 'undefined' is not a function
This is a larger js application, and this error message is totally unhelpful. Is there any way I can get the line number of the error or anymore information?
Update: This just got funky.
line : 0
page : undefined
desc : TypeError: 'undefined' is not a function
chr : undefined
Did the user agent spoofing in FF and safari. No error.
You could try registering a custom error handler to window.onerror
window.onerror = function (desc,page,line,chr)
{ alert('Line:'+line); }
desc = Error message
page = File/Page where the error occured
line = Well...
chr = Character position of the error in the line
If you bind an error handler to window.onerror, it should give you the line number, e.g.
window.onerror = function(msg,url,line) {
alert('The error is on line '+line);
}
This question: Debug JavaScript errors on iPad seems to indicate you can enable debugging too.
If the script is loaded dynamically, though, it can be hard to get such info in any environment.
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.