Why "fail" in promise does not catch errors? - javascript

I'm trying to access a file, that might not exist:
var localFolder = Windows.Storage.ApplicationData.current.localFolder;
localFolder.getFileAsync(stateFile).then(function (file) {
Windows.Storage.FileIO.readTextAsync(file).then(function (text) {
// do something with the text
});
}, function (err) {
// log error, load dummy data
});
if the file is not there, the "fail" method does get called, BUT it happens only AFTER my application halts with an exception "file not found". only when I press "continue" for the debugger does it continue to the "fail" method..
what am i doing wrong? should i check for existence beforehand?

You're seeing a first-chance exception. The debugger is breaking at the point of throw. If you hit the "continue" button on the debugger dialog, the app will keep running and the exception handler will run.
You can change this by using the "Debug|Exceptions" menu to turn off first chance exceptions.

I have been struggling with this same problem for two or three days and finally came to the following solution: I use getFilesAsync function to get the list of all files in a folder, and then look through this list to know if the needed file exists. After that I can call getFileAsyns without throwing. Not very pretty, but works for me. I agree that assuming that a developer can turn exceptions off is not the best advice... In my opinion this issue should be considered as a bug in RT implementation.

Related

Writing to csv-file with npm csv-writer not working, but no error message appearing

I am trying to write to a CSV-file from my electron renderer.js process. Unfortunately, most of the time the writing isn't working, and the .then addition isn't executed. Strangely, there is no kind of error message or anything that would tell me my mistake. Some few times it has worked though, the file was written but the confirmation from .then wasn't displayed in the console. I don't have any clue as to what went differently these times.
When reloading the application with ctrl+r after the failed attempt the saving process is run again (somehow the onclick attribute of a button, containing a function call for the function all this stuff here ↓ is in) and that always works (including the .then call).
My code:
var settings = [
["devtools", false, devtools, ""],
["language", "en", language, ""]
]
var csvWriter = window.createCsvWriter({
header: ['ABBREVIATION', 'DEFAULT', 'CUSTOM', ''],
path: 'saves/settings.csv'
});
csvWriter.writeRecords(settings)
.then(() => {
console.log('Saved succesfully!');
});
window.createCsvWriter is a preloaded script, devtools and language are script wide variables that are updated shortly before this.
I have no idea where the error is coming from, as it can't be in the path or something like that as it has run successfully multiple times. I even tried to follow the debugging process line by line, but all I think I have found out is that the settings array is fully dealt with, the script ends somewhere in a jungle of loops and if-clauses concerning the path or something.
I also know that a normal CSV-file wouldn't have a comma on the end of the rows, my code importing the settings later just can't deal with that, which I will fix later. If you need any more information just ask.
EDIT:
I just followed the code again line by line and notices that it stops after the return __awaiter() in CsvWriter.prptotype.writeRecords = function (records) {...}. records is an array with the correct data for the CSV. Maybe that is useful information.
EDIT2:
I tried using fs.writeFile() to write and it has the same problem, the file became empty and there was no error. I noticed though, that when reloading (remember originally it worked when reloading) it sent errors or confirmations for all the attempts of that session at once, and the file was written (if there were confirmations). So I assume the problem is something that stops the code from fully running until the page is reloaded. Any ideas what that could be? I imagine it's possible that it's another script or something global.
I don't have any breakpoints stopping the code.
writeRecords returns a promise that is either resolved or rejected. You code only handles the 'resolved' path and you ignore any rejection. Try this, it could reveal the error:
csvWriter.writeRecords(settings)
.then(() => {
console.log('Saved succesfully!');
})
.catch((err) => {
console.log('Save failed', err);
});

Unhandled exceptions in Google Apps Script

I have created a public Web App with access to my private spreadsheet data. I can catch and log exceptions intry..catch, but:
is it possible to catch all unhandled exceptions, like browsers window.onerror?
can I view logs of unhandled exceptions somewhere?
by exceptions like "Service invoked too many times" my app is even not getting run, so here I definitely can`t handle the exceptions. Is there logs with such kind of exceptions?
These are so simple questions, so that I'm bit confused to ask them, but after hours of research I could not find the answers.
Thank you in advance.
These are issues that are being addressed currently. Right now in the Apps Script Early Access Program are two new additions that handle these cases. The first is native integration with stackdriver logging and the addition of google.script.run.withLogger().
First off for now you need to apply for the EAP:
https://developers.google.com/apps-script/guides/apps-script-eap
Stackdriver Logging:
To log to stackdriver the console object has been added to the server side.
code.gs
console.log('This will log to stackdriver')
Check out the docs for all the methods of console.
https://developers.google.com/apps-script/guides/logging#stackdriver_logging
Example from the docs:
function measuringExecutionTime() {
// A simple INFO log message, using sprintf() formatting.
console.info('Timing the %s function (%d arguments)', 'myFunction', 1);
// Log a JSON object at a DEBUG level. The log is labeled
// with the message string in the log viewer, and the JSON content
// is displayed in the expanded log structure under "structPayload".
var parameters = {
isValid: true,
content: 'some string',
timestamp: new Date()
};
console.log({message: 'Function Input', initialData: parameters});
var label = 'myFunction() time'; // Labels the timing log entry.
console.time(label); // Starts the timer.
try {
myFunction(parameters); // Function to time.
} catch (e) {
// Logs an ERROR message.
console.error('myFunction() yielded an error: ' + e);
}
console.timeEnd(label);
}
In addition you can also check Log Exceptions in the scripts properties. This will generate a stackdriver entry every time any error occurs in your script.
Error recovery in a web app
To recover in a web app from a failure you have access to the withFailureHandler() method found in the google.script.run object. With this you can register a callback in the event your script hits an exception.
Full documentation can be found at:
https://developers.google.com/apps-script/guides/html/reference/run
If you are doing server side checks with try...catch you may be getting an exception but gracefully handling it. In this case withFailureHandler() will not execute and onSuccessHandler() propably isnt the best place to handle errors. In the EAP there is now a withLogger method to google.script.run. For now there no documentation for google.script.run.withLogger(). I found it by digging through devtools. withLogger() allows you to register a function as a callback when ever a stackdriver entry is created. This is particularly helpful when you have log exceptions checked in your script properties. In this sense it is a bit like withFailureHandler() but it can be triggered by any stackdriver entry you add though the server-side console object.
index.html
<script>
google.script.run
.withSuccessHandler(function(){console.log('OK')})
.withFailureHandler(function(e){console.error(e)})
.withLogger(function(e){console.warn("The following log was generated:"+e)})
.serverFunctionCall();
</script>
code.gs
function serverFunctionCall(){
console.log("This log will generate a callback");
return true;
}
Try/catch at global scope will work, however any let/const container will not be globally exposed.
To fix this, you can use var within the try/catch at global scope

How to handle UnexpectedAlertOpenError in Protractor

I'm working on the automation of a website and i ran into a particular problem.
I'm using protractor over gulp to run the automated tests and also a report generator included in the gulp task.
The issue at hand is the following:
Whenever an alert is triggered by chrome, protractor stops and throws the "UnexpectedAlertOpenError" in the console, stopping the test run and canceling the report generation.
I would like to know if there is a way to make the spec fail and continue running the rest of the suite.
I know you can do this:
browser.get(url).catch(function () {
return browser.switchTo().alert().then(function (alert) {
alert.accept();
return browser.get(url);
});
});
But i don't want protractor to close the alert and continue, I would like to fail the test where it came up, and return an error message to continue with the run.
Is there any way to do that? Is it possible to pass an exception to the catch function and return a message? I could not find any documentation about that catch method.
Thank you!
EDIT: After going over the stack trace on the console, I've found that protractor detects as if the spec failed, and the exception comes from the reporter when it tries to take a screenshot (I'm using protractor-jasmine2-html-reporter)
I'm going to paste a bit of the stack trace in case someone can figure out something, I'm lost really.
E/launcher - UnexpectedAlertOpenError: unexpected alert open: {Alert text : You have pending changes}
From: Task: WebDriver.takeScreenshot()
EDIT2: I found the real problem with my implementation. The npm plugin protractor-jasmine2-html-reporter (which i'm using) was trying to take a screenshot when the alert was open, causing the webdriver to break and the kept the report from being generated.
What i did to fix this was to fork from their repository and before trying to take a screenshot confirm if the alert was open and avoid taking the screenshot if it was:
function alertIsPresent() {
return browser.driver.switchTo().alert()
.then(function (alert) {
alert.accept();
return true;
}, function (err) {
return false;
});
};
In case it was open, i would close it and continue without taking the screenshot, otherwise take the screenshot.
By doing this the report generates correctly and it documents that on the next spec report that there was an alert open.
Hope this is helpful to someone.
I've had a similar problem. Searched for hours and finally found this:
unexpectedAlertBehaviour: 'accept'
See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities#read-write-capabilities for more information. You basically create a capabilities object and pass the desired values into it:
capabilities: {
browserName: "chrome",
unexpectedAlertBehaviour: 'accept',
chromeOptions: {
args: ["--window-size=1920,1080", "--disable-gpu"],
},
},
Hope this helps!
You should be able to check for these Error codes and force a failure via the jasmine fail function
browser.switchTo().alert().then(function(alert) {
alert.accept();
}, function(err) {
if (err.code == webdriver.error.ErrorCode.UNEXPECTED_ALERT_OPEN) {
fail('Fail this spec');
}
});
This is odd that your test Protractor test completely fails and Protractor stops working. If this is the case, please feel free to open up a Protractor issue.
My guess is that you have an it spec that fails, and it puts up an alert causing other tests to not work. There are a couple of things you could do:
Restart the browser after each test (see the config). This quits the driver session and creates a new browser instance. As you can imagine, this will slow down your test. In your config set:
restartBrowserBetweenTests: true
Try using the postTest plugin. Use postTest to check if the test failed, and maybe check if there is an alert and close it.
postTest: function(passed, testInfo) {
if (!passed) {
// should check to see if there is an alert
// close the alert
return browser.switchTo().alert().then(function (alert) {
return alert.accept();
});
}
}

wirecloud / fiware "Not registered callback" although callback function is implemented

I made a widget for the filab and everytime it gets executed it shows me the following error:
I got that error a few times before, it always was a syntax error in my code.
But by now ( I think they updated the filab last days) the filab catches this errors, too, and shows where the error is.So this time there must be another problem.
Does somebody else got such a problem and knows how to solve it?
Code in main.js
the callback function is implemented in the main.js, too.
Code in config.xml
WireCloud is complaining about an input endpoint identified as "INPUT2", while you are providing us the code you use for registering "INPUT1".
There is another strange thing, you are registering the callback using this line:
MashupPlatform.wiring.registerCallback("INPUT1", callback(this));
I'm guessing the correct line is:
MashupPlatform.wiring.registerCallback("INPUT2", callback);
Or:
MashupPlatform.wiring.registerCallback("INPUT2", callback.bind(this));

Continue test if a click error occurs

I'm running CasperJS with PhantomJS. I have it going to a url and clicking on an element based on XPath. This could happen several times without a problem, until, I suspect there is a delay in the page loading, it can't find the XPath, it throws an error and stops the test. I would like it to continue through the error. I don't want to wait+click any longer than I already am, as there are many clicks going on, and an error can be at a random click, waiting on every click is counter productive.
I have tried putting the whole test into a try catch, it wouldn't catch.
The only handling I could find just gave out more information on the error, still stopped the test.
I would wait for the selector you want to run, with a short timeout. In the success function do your click, in the timeout function report the problem (or do nothing at all).
For instance:
casper.waitForSelector('a.some-class', function() {
this.click('a.some-class');
}, function onTimeout(){
this.echo("No a.some-class found, skipping it.");
},
100); //Only wait 0.1s, as we expect it to already be there
});
(If you were already doing a casper.wait() just before this, then replace that with the above code, and increase the timeout accordingly.)
You cannot catch an error in something that is executed asynchronously. All then* and wait* functions are step functions which are asynchronous.
Darren Cook provides a good reliable solution. Here are two more which may work for you.
casper.options.exitOnError
CasperJS provides an option to disable exiting on error. It work reliably. The complete error with stacktrace is printed in the console, but the script execution continues. Although, this might have adverse effects when you also have other errors on which you may want to stop execution.
try-catch
Using a try-catch block works in CasperJS, but only on synchronous code. The following code shows an example where only the error message is printed without stacktrace:
casper.then(function() {
try {
this.click(selector);
} catch(e){
console.log("Caught", e);
}
});
or more integrated:
// at the beginning of the script
casper.errorClick = function(selector) {
try {
this.click(selector);
} catch(e){
console.log("Caught", e);
return false;
}
return true;
};
// in the test
casper.then(function() {
this.errorClick("someSelector");
});

Categories