I try to improve my code so that I don't have to program a try - catch block all the time.
e.g. at the moment I have to write many codeblocks like this:
try {
$login_feld = $SeleniumObj->driver->findElement(WebDriverBy::id("login_feld"));
} catch(NoSuchElementException $exception) {
$SeleniumObj->setErrorMessage("1 ID login_feld does not exist.", $exception, true, "login_field");
break;
}
try {
$password_field = $SeleniumObj->driver->findElement(WebDriverBy::id("password_field"));
} catch(NoSuchElementException $exception) {
$SeleniumObj->setErrorMessage("1 ID password_field does not exist.", $exception, true, "login_field");
break;
}
try {
$field3 = $SeleniumObj->driver->findElement(WebDriverBy::id("field3"));
} catch(NoSuchElementException $exception) {
$SeleniumObj->setErrorMessage("1 ID field3 does not exist.", $exception, true, "login_field");
break;
}
My goal is to reduce this to one line.
Therefore I outsourced the whole driver->findElement(WebDriverBy::id("xy")); to a new function from the class Selenium called ById
/**
*
* @param id $id
* @param bool $takeScreenshot
* @return void
*/
public function ById($id, $takeScreenshot=false)
{
try {
return $this->driver->findElement(WebDriverBy::id($id));
} catch(NoSuchElementException $exception) {
$this->setErrorMessage("ID '$id' does not exist.", $exception, $takeScreenshot, $id);
//break; <- does not work in this context
}
}
Now theoretically I can code the whole block like this:
$login_feld = $SeleniumObj->ById('login_feld', true);
$password_field = $SeleniumObj->ById('password_field', true);
$field3 = $SeleniumObj->ById('field3', true);
However, one problem still persist. I can't call break in the exception block in the function ById, otherwise I get
break' not in the 'loop' or 'switch' context
Now to solve this I could instead return a status, e.g. false if the code reached in the exception block and then check this before proceeding
/**
*
* @param id $id
* @param bool $takeScreenshot
* @return void
*/
public function ById($id, $takeScreenshot=false)
{
try {
return $this->driver->findElement(WebDriverBy::id($id));
} catch(NoSuchElementException $exception) {
$this->setErrorMessage("ID '$id' does not exist.", $exception, $takeScreenshot, $id);
return false;
}
}
-
$login_field = $SeleniumObj->ById('login_field', true);
if ($login_field == false) { break; }
$pw_field = $SeleniumObj->ById('pw_field', true);
if ($pw_field == false) { break; }
$field3 = $SeleniumObj->ById('field3', true);
if ($field3 == false) { break; }
But now I need two lines per block instead of one. Is it possible to improve this even further?