How do I catch Selenium Errors using WebDriverJS

bagelmaker's suggestion of using findElements is not a bad one. That's usually what I do when I want to check whether an element exists rather than fiddle with exceptions.

However, for the sake of completeness, here is how you'd deal with the error generated when an element does not exist:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

driver.get('http://www.google.com');

driver.findElement(webdriver.By.id("fofofo")).then(null, function (err) {
    if (err.name === "NoSuchElementError")
        console.log("Element was missing!");
});

driver.quit();

The second argument to then is an errback which is called if findElement fails. Because selenium-webdriver operates with promises, this is how you have to catch the error. Using try...catch cannot work because Selenium does not start working right away; the work that you ask Selenium to do with findElement is performed at an undetermined time in the future. By that time the JavaScript execution would have moved out of your try...catch.

The code above searches for an element with an id value of fofofo, which does not exist and fails.


You can also catch that error in a chained "catch" method:

driver.findElement(webdriver.By.id("fofofo")).then(() => {
    // do some task
}).catch((e) => {
    if(e.name === 'NoSuchElementError') {
        console.log('Element not found');
    }
})

And if you're using async/await, you can do something like:

try {
  await driver.findElement(webdriver.By.id("fofofo"));
  // do some task
}
catch (e) {
  if (e.name === 'NoSuchElementError')
    console.log('Element not found');
}