How to correctly catch PHP exceptions (Laravel 5.1)

I have code that makes db calls and network requests, and I wrapped them in try / catch. The problem is that I can never catch exceptions, and they don't seem to be fatal exceptions:

try { // make db requests and network calls } catch (Exception $e) { // handle exception } 

Namely, I encounter exceptions such as:

 [Illuminate\Database\QueryException] [PDOException] [InvalidArgumentException] 

Is there any way to catch these exceptions? Do I need to be explicit for every possible type of exception object (which means I have to create many attempts / catch), or is there a recommended way to catch non-fatal exceptions?

+7
php exception eloquent laravel laravel-5
source share
1 answer

Make sure you use the namespace correctly.

If you use a class without providing your namespace, PHP looks for the class in the current namespace. An exception exists in the global namespace, so if you do, try / catch in some code with a name extension, for example. your controller or model, you will need to do:

 try { //code causing exception to be thrown } catch(\Exception $e) { //exception handling } 

If you do this like that, there is no way to skip any exceptions.

Otherwise, if you get an exception in the controller code stored in the \ Http \ Controllers application , your catch will wait for the App \ Http \ Controllers \ Exception object to be thrown.

+16
source share

All Articles