0

What's the proper way to catch exceptions using the PHP Webdriver? I have something like this:

try {
    // Throws a NoSuchElementException if id doesn't exist 
    $driver->findElement(WebDriverBy::id('loggedIn'));
    return TRUE;
}
catch (NoSuchElementException $e) {
    // id='loggedIn' doesn't exist
    return FAlSE;
}
catch (Exception $e)
{
    // Unknown exception
    return FALSE;
}

However, when I reach a page and do not find the element with the id I'm looking for, I get the following error:

Uncaught Facebook\WebDriver\Exception\NoSuchElementException: Unable to locate element: #loggedIn

I'm not sure why as my code is wrapped in a try-catch block.

3 Answers 3

4

I would suggest you avoid try..catch and check whether the element is on the page without getting an exception, just try using findElements instead which would return either an array of all elements with matching locator or empty array if nothing is found, so you need to just check the array count to determine that element exists or not as below :-

if (count($driver->findElements(WebDriverBy::id("loggedIn"))) > 0) 
{
  return TRUE;
}else 
{
  return FALSE;
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's a possible workaround for findElement, but it doesn't answer why I'm not able to catch exceptions.
Ok make sure you are catching right NoSuchElementException. Verify first are you imported correct class for NoSuchElementException??
And also make sure exception is throwing from this code or some other code which is not inside try..catch block??
4

this works for me, hope this helps someone

try {
    ...
} catch (Exception\NoSuchElementException) {
    ...
}

Comments

0

I am not sure , why neither Exception, nor specific exception does not work , but :

catch (WebDriverException $e)

works for me )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.