How to properly catch PHP exceptions (Laravel 5.1)

2019-01-27 22:50发布

问题:

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

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

Namely, I encounter exceptions such as these:

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

Is there a way to catch these exceptions? Do I need to be explicit for each possible type of exception object (meaning I must create many try/catches), or is there a recommended way of catching non fatal exceptions?

回答1:

Make sure you're using your namespaces properly, by including the Exception class at the top of your controller like this:

 Use Exception; 

If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exception class exists in global namespace, so if you do that try/catch in some namespaced code, e.g. your controller or model, you'll need to do:

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

If you do it like this there is no way to miss any exceptions.

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