nabilunfarhanun's avatar

How to handle exception inside controller?

I am trying to upload a file. And if it throws an exception I don't want to see the "whoops" page. Instead it will go back the previous page with a message. This is what I tried,

try {
    $data = Excel::toArray(new Import, request('file'));
} catch (\Exception $e) {
    return back()->withErrors("an exception occured");
}

But it still gives me the whoops page whenever any exception occurs.

This is the exception I am getting(for testing I purposefully limited the memory size)

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Allowed memory size of 62914560 bytes exhausted (tried to allocate 14680064 bytes)

How to solve it?

0 likes
2 replies
bobbybouwmann's avatar

You probably get a 500 server error and therefore you always get the whoop page.

Looking at your code I can only see one mistake. The second argument of the toArray method should be a file, but it's now a string.

Try this instead

$data = Excel::toArray(new Import, request()->file('file'));

You can find the errors in the storage/logs directory. So if you get a whoops, you can see what error the code gives you ;)

Snapey's avatar

Memory issues are particularly hard to catch because PHP has no memory left to handle the exception process.

Please or to participate in this conversation.