Home > Net >  PHP - method/function throws an exception in a loop. How to continue iterating while calling this me
PHP - method/function throws an exception in a loop. How to continue iterating while calling this me

Time:10-28

I have an class that has a private method. There is a loop inside this method where an exception can be thrown:

private function getAliasesFilters(): array
{
    $filters = ...
    $aliasesFilters = array();

    if (is_array($filters)) {
        foreach ($filters as $filter) {
            if (array_key_exists($filter['alias'], $aliasesFilters)) {
                $msg = sprintf(
                    'More than one filter with an alias "%s "was found!',
                    $filter['alias']
                );
                throw new FilterException($msg, FilterException::MULTIPLE_ALIAS);
            }

            $aliasesFilters[$filter['alias']] = $filter['filter_id'];
        }
    }

    return $aliasesFilters;
}

And this method is called by another method that looks like this:

public function getFilters(): array
{
    $filters = $this->getAliasesFilters();

    foreach ($filters as $alias => $id) {
        $filters[$alias] = new FilterDefiniton($id);
    }

    return $filters;
}

and in other class I call getFilters, but I need the iteration over the error handling to continue where it left off.

The perfect way will be something like that, but it insn't possible:

try {
    $this->filters = $x->getFilters();
} catch (FilterException $e {
    if ($e->getCode === FilterException::MULTIPLE_ALIAS) {
        // log or something
        continue; // But this isn't iside the loop so I will get an Error ;c
    } else {
        ...
    }
}

I need to continue iterate inside that function but with skiping this element. Unfortunately, I can't change the code of that class (the one with iteration) and I have to handle it somehow in my try and catch.

Is such a thing even possible? Every time I call this method, I get the exception in exactly the same place, and I can't skip over it.

I tried to do the method and after catching the exception, execute the method again, but it starts iteration all over again ... and throws the same exception in the same line with the same item ...

Any ideas?

CodePudding user response:

you must extend class and rewrite getAliasesFilters()

CodePudding user response:

Unfortunately that what you want is not possible in this situation. Your solutions in my opinion is: Your own class with functions where you will return same aliases without exception

  • Related