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

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 );
}

Related

HtmlUnit JavaScript Issue on page load - Cannot find function

I'm crawling website secured with Cloudflare and sometimes getting an error due to redirection to page with ReCapcha, the page cannot be even loaded due to some javascript error. The code is failing on #getPage method and i have no idea why.
Here is the code works fine for normal pages, but fails on confirmation page:
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setJavaScriptEnabled(true);
final HtmlPage page = webClient.getPage("https://mydummy.site");
webClient.waitForBackgroundJavaScript(10000);
int waitForBackgroundJavaScript = webClient.waitForBackgroundJavaScript(200);
int loopCount = 0;
while (waitForBackgroundJavaScript > 0 && loopCount < 2) {
++loopCount;
waitForBackgroundJavaScript = webClient.waitForBackgroundJavaScript(200);
if (waitForBackgroundJavaScript == 0) {
break;
}
}
Logs:
java.lang.RuntimeException: com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot find function start in object [object MessagePort]. (https://www.gstatic.com/recaptcha/api2/v1536705955372/recaptcha__en.js#249) (https://www.gstatic.com/recaptcha/api2/v1536705955372/recaptcha__en.js#253)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:305)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:539)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:399)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:316)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:467)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:449)
at Main.htmlUnit(Main.java:156)
at Main.main(Main.java:43)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: Wrapped com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot find function start in object [object MessagePort]. (https://www.gstatic.com/recaptcha/api2/v1536705955372/recaptcha__en.js#249) (https://www.gstatic.com/recaptcha/api2/v1536705955372/recaptcha__en.js#253)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:892)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:616)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:532)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:772)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:748)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:104)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:992)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:371)
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:246)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:298)
We have been struggling with this issue as well. Our test suite ran perfectly until late 2018 when this issue broke all of our logins. I believe Google has put this in deliberately to break automated attempts to break captchas, because solving one part of this seems to only lead to another problem. Both loading the page and submitting the page causes issues, even if you tell HtmlUnitDriver to ignore all JavaScript errors.
I have tried several options at this point. If you use the Google specified test site key, then the errors go away. So if you have full server-side control of how that site key is generated, you are OK. Remember to ensure that the test site key shows up again on validation errors and all similar use cases, otherwise you will get that error.
(Unfortunately for us, our login page is plain JSP and so implementing this is a headache unless we want to change the URL everywhere. Still debating what to do, for right now we do have a workable if ugly solution that involves some conditional logic on the page and catching JavaScript exceptions at other points in the test code.)

Swift JavaScriptCore not working with large files?

https://github.com/gg2001/monero/blob/master/monero/NewWallet.js
I have a js file that is quite large 6000 lines and JavaScript core does not seem to be able to retrieve variable values whereas running the same file in any web browser works fine for me. When I try to retrieve the value of a variable it shows up as undefined, but when I use a js console in a browswer it shows up fine. I am speculating that this is due to the size of the file because when I put
var helloWorld = "Hello World";
in the front of the js file this swift code can retrieve it
func helloWorld() {
if let variableHelloWorld = self.jsContext.objectForKeyedSubscript("helloWorld") {
print(variableHelloWorld.toString())
}
}
but when I put it at the end it cannot.
Normally this indicates a parsing error. Try adding an error handler to self.jsContext before calling objectForKeyedSubscript() and see if it outputs anything insightful.
self.jsContext.exceptionHandler = { context, exception in
print("JS Error: \(exception?.description ?? "unknown error")")
}
Although your JS code may be valid in a browser console, iOS Safari doesn't support as many Javascript features as newer browsers.
I did see a line in your JS source code beginning with just a semicolon (followed immediately by (function). I wonder if the parser might complain about an empty line without a statement..? Maybe nothing, though.

In Netsuite, ReferenceError nlapiCreateFile and nlapicreatecsvimport is not defined

In netsuite, I write the these code but I face a problem as
ReferenceError nlapiCreateFile is not defined
Code:
function creatingFile() {
var file = "xxxxx";
var fileObj = nlapiCreateFile('mycsv.csv','CSV',file); // Error !!!
nlapiSendEmail(15,'epost#xx.com,"subject" ,fileObj, null, null, null, null);
}
I have some similar old 1.0 code that works just fine. From a quick glance that is probably failing due to the "file" variable not being defined, and you have an extra apostrophe in the nlapiSendEmail function. Is that defined as a global variable earlier on in your script, also is "x" defined as an email address or internal ID?
Try running it with some try catch statements to get more specific error information. This should give you enough information for debugging where your problem is at.
function creatingFile(){
var fileContents='ASDFASDf,asdfgasfasdf';
var folderID='12345'; //replace with a valid folder internal ID.
try{
var fileObj=nlapiCreateFile('mycsv.csv','CSV',fileContents);
fileObj.setFolder(folderID);
var fID=nlapiSubmitFile(fileObj);
}catch(err01){
nlapiLogExecution('DEBUG','ERROR 01',JSON.stringify(err01));
}
try{
nlapiSendEmail(15,x,"asd",fID,null,null,null,null);
}catch(err02){
nlapiLogExecution('DEBUG','ERROR 02',JSON.stringify(err02));
}
}
I believe you are running into what I would consider a "bug", but NetSuite may disagree. If you are calling your creatingFile() function from a user event (i.e. a button on the Suitelet form, etc), that seems to fall under the category of "client script" in NetSuite logic, and the nlapiCreateFile function is not available in Client script context. This is not at all intuitive because, from my perspective, it's all part of the Suitelet, which is supported for that function. The only way I found to work around it is to create the file on load of the script, not on action of the user. However, this has resulted in other issues I haven't figured out yet, such as how I use the newly created file object in the client context once the customer clicks the button (I'm trying to send the file as an email attachment).

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

Javascript debugging in Safari web browser

I have a JavaScript error in my web project, and this error appears only in Safari 5 web browser. And the problem is Safari says just error message, but not file and line where this error appears. So, I can't find which code cause this error. Does anybody know how can I find code line causes this error?
Here is shot with debugger.
http://xmages.net/storage/10/1/0/d/c/upload/691ce801.png
Thanks for helping.
Click on the "stop sign" icon until it turns blue and then rerun the code. This should make the debugger halt on the line that generated the exception (and allow you to inspect the local variables and execution stack at that point).
thanks for helping!
Problem resolved now. It was jQuery template plugin. It causes this error when some DOM element in template has ID same as template variable name.
E. G.
var template = "<div id="foo">${foo}</div>"
var data = {foo: "bar"}
$.tmpl(template, data)
Solution: Rename ID of template variable name.
var template = "<div id="foo">${bar}</div>"
var data = {bar: "bar"}
$.tmpl(template, data)

Categories

Resources