问题
I was using Protractor and Cucumber and noticed that there were instances where I wanted to capture a NoSuchElementError: No element found using locator: By.cssSelector("someCssLocatorHere")
. However, using the traditional try/catch block wouldn't work unless I called both the callback and errBack of the .then() function and throw the error so that I can catch it later like following:
try{
somePromise.then(function(){
//callback function if promise gets resolved successfully
}, function(e){
console.log(e); //errBack in case promise gets rejected or fails
throw e; <--------------- THROW error here so can catch it in catch block below
});
}catch(e){
console.log('error:'+e);
}
And the above solution was/is suggested by many answers on Stackoverflow. So I don't have any question but I am going to answer to my own question below to show you the proper way to handle this exception (NoSuchElementError: No element found using locator: By.cssSelector("someCssLocator")
) without explicitly wrapping your code with try/catch blocks.
回答1:
I ran into this problem recently and noticed that you DONT need the try/catch block. In Protractor, you can achieve the try/catch like following:
try { <---------------------------- Traditional TRY/CATCH method
loadWebApp();
login();
openUserPreferences();
changePassword();
} catch (err) {
console.error(
"An error was thrown! " + err);
}
loadWebApp().
then(login).
then(openUserPreferences).
then(changePassword).
then(null, function(err) { <----------------- PROTRACTOR equivalent of try/catch
console.error(
"An error was thrown! " + err);
});
Here's the source where I got this info from: https://code.google.com/p/selenium/wiki/WebDriverJs#Promises
under Value Propagation and Chaining
So again, you don't need to explicitly add a try/catch.
In short, the reason this method works is because a promise can either be RESOLVED or REJECTED and in case of a rejected or failed promise, this line [ then(null, function(err) { ... } ] will act as the CATCH block.
Also notice that the then(null, function(err))( is NOT taking any callback (instead NULL) but only an errBack; so basically, this is saying we don't care about whether the promise gets resolved, we only care about whether it fails and thus the NULL for callback and the function(error) for the errBack. No need to wrap this in a try/catch then throw the error as suggested by many answers on Stackoverflow.
Hope this helps someone out there struggling with this in Protractor as I did.
来源:https://stackoverflow.com/questions/34775443/protractor-try-catch-issues