Reputation: 65
So I'm using the JavaScript implementation of Selenium, WebDriverJS. I'm rather new to WebDriverJS, and I'm wondering, why does the code crash within a Try block? It never even gets to the Catch block. Here is my code:
try
{
driver.findElement(this.By.xpath("html/body/form/div[4]/div[1]/center[1]/div[15]/div[1]/a[1]/img[1]")).click();
catch (err)
{
driver.findElement(this.By.xpath("html/body/form/div[3]/div[1]/center[1]/div[15]/div[1]/a[1]/img[1]")).click();
}
Then I get this error message in the console:
NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/form/div[4]/div[1]/center[1]/div[15]/div[1]/a[1]/img[1]"}
As you can see, this error comes from the code within the Try block.
Is there any way I can make the code continue executing despite this error?
Upvotes: 2
Views: 377
Reputation: 494
WebdriverJS fires off "findElements" asynchronously (docs here), which means that your statement will clear that try catch, then the callback throws an error. To catch the error properly, use the promise pattern:
// Original implementation
driver.findElement({id: 'my-button'}).click();
// Promise usage, my preference
driver.findElement({id: 'my-button'}).then(function(el) {
return el.click();
}).catch(function(err){
//handle error here
})
// Another way to resolve the error
driver.findElement({id: 'my-button'}).then(el, function (err) {
if (err && err.name === "NoSuchElementError"){
return console.log("Element was missing!");
}
return el.click();
});
Upvotes: 1