exception - Error handling inside PHP generator function


Related: Error in PHP Generator

How do I propagate errors in a generator function without stopping iteration?


class SynchronizeSchedules extends \Symfony\Component\Console\Command\Command
    protected function execute(InputInterface $input, OutputInterface $output): void {
        $synchronizer = new \ScheduleSync();
        foreach ($synchronizer->sync() as $schedule) {
            $output->writeln("Schedule {$schedule->id} synchronized");

class ScheduleSync
    public function sync(): \Generator {
        $data = [/* data from somewhere */];

        foreach ($data as $d) {
            try {
                // insert into database
                yield $d;
            } catch (DBALException $e) {
                // something went wrong

If a database error (DBALException) occurs, I want to do something. For example in the CLI command (Symfony Console) I'd like to write to STDOUT. When invoked in the web application, logging the error to a file or something would be more appropriate.

Apart from passing a LoggerInterface object into the class that has a generator method, is there a clean way of dealing with this?

People are also looking for solutions to the problem: sql - PHP: How to count values from database and create a top 10 leaderboard of counted


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.