exception - Error handling inside PHP generator function
Related: Error in PHP Generator
How do I propagate errors in a generator function without stopping iteration?
Example:
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
$this->db->insert('...');
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?