Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KikoLdasd's avatar

Continue try catch if you have errors

Hi, I would like to continue downloading an excel even if I have errors. How can I continue the loop even if there are errors and I can download excel? Here's the code

foreach ($participants as $k => $participant) {
                    $media = '';
                    if ($participant->id != 430) {
                        $media = DB::table('media')->where('collection_name', 'prize_signature')->where('model_id', $participant->id)->first();   
                    }
                    $row = $k+2;
                    $event->sheet->getRowDimension($row)->setRowHeight(40);
                    $drawing = new Drawing();
                    $drawing->setName('Logo');
                    $drawing->setDescription('This is my logo');
                    if ($media != null) {
                       $drawing->setPath("public/storage/{$media->id}/signaturePrize.png");   
                    }
                    $drawing->setHeight(40);
                    $drawing->setCoordinates("M{$row}");
                    $drawing->setWorksheet($event->sheet->getDelegate());
                
                }
0 likes
5 replies
Snapey's avatar

What errors might you have?

Obviously you could wrap the entire block above in try-catch and continue if something went wrong, however some of the actions will have already been performed depending on where the error occurred.

oh, by the way, its a cause for concern to see URLs in your code, especially urls that contain public since public should never be present in URLs, and you make this code such that it is not portable.

Sinnbeck's avatar

You can wrap it, but I cannot garantee that the sheet wont be affected

foreach ($participants as $k => $participant) {
           try {
                    $media = '';
                    if ($participant->id != 430) {
                        $media = DB::table('media')->where('collection_name', 'prize_signature')->where('model_id', $participant->id)->first();   
                    }
                    $row = $k+2;
                    $event->sheet->getRowDimension($row)->setRowHeight(40);
                    $drawing = new Drawing();
                    $drawing->setName('Logo');
                    $drawing->setDescription('This is my logo');
                    if ($media != null) {
                       $drawing->setPath("public/storage/{$media->id}/signaturePrize.png");   
                    }
                    $drawing->setHeight(40);
                    $drawing->setCoordinates("M{$row}");
                    $drawing->setWorksheet($event->sheet->getDelegate());
           } catch (\Exception $e) {
                       //Do nothing.. So just continue
           }
                
}

Please or to participate in this conversation.