How to properly catch PHP exceptions (Laravel 5.1)

10,074

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.

Share:
10,074
Joel Joel Binks
Author by

Joel Joel Binks

PHP/MySQL/Node/JS/JQuery/HTML/CSS/Java/Python

Updated on June 16, 2022

Comments

  • Joel Joel Binks
    Joel Joel Binks almost 2 years

    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?

  • Joel Joel Binks
    Joel Joel Binks almost 9 years
    Ah. Looks like a careless error on my part. I will try this and if it works I will choose this answer.
  • ssi-anik
    ssi-anik about 8 years
    I've intentionally tried Apps\MyModel to find a record, it's throwing class "Apps\MyModel" not found exception. I tried the both FatalErrorException and \Exception, both failed. any idea?