swarajgiri's avatar

L5: Catch exception in class

I am building a REST API which handles csv file uploads. Basically, i am trying to check if a string is valid for DateTime constructor and in case its not, respond with an error instead of throwing an exception.

Here is what the code looks,

Inside a foreach loop
try {
    $date = new \DateTime('2013-10-30 - 12:08:32'); // invalid format
} catch (Exception $e) {
    $errors[] = 'Invalid purchase date format';
    continue;
}

Issue is the execution skips this step and jumps to App\Exceptions\Handler. Is there a way i could prevent it from doing so?

0 likes
11 replies
bestmomo's avatar

Your continue is not correct in this context. Which error do you get ?

deadlockgB's avatar

Add the exception you don't want to be reported to the

protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

array in /app/Exceptions/Handler.php

bestmomo's avatar

@swarajgiri I try that :

try {
    $date = new \DateTime('2013-10-30 - 12:08:32'); // invalid format
} catch (Exception $e) {
    dd('I am here');
}
pmall's avatar

Yes it should work, exception handler gets in when an exception isnt caught.

swarajgiri's avatar

@bestmomo - Tried that on the first line of a controller. Still get the whoops screen with the exception.

swarajgiri's avatar
swarajgiri
OP
Best Answer
Level 1

@bestmomo - Problem of the missing \. \DateTime instead of DateTime. (facepalm)

try {
    $date = new \DateTime('2013-10-30 - 12:08:32'); // invalid format
} catch (\Exception $e) {
    dd('I am here');
}

Please or to participate in this conversation.