Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly catch PHP exceptions (Laravel 5.1)

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?

like image 599
Joel Joel Binks Avatar asked Jul 20 '15 02:07

Joel Joel Binks


People also ask

How can I catch exception in PHP?

Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }

Which is the correct way to use catch block in PHP?

Catch: This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown. Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified after or instead of catch blocks.

How do I get exception error in Laravel?

In Laravel 5 you can catch exceptions by editing the render method in app/Exceptions/Handler. php . This will be applied to ANY exception in AJAX requests. If your app is sending out an exception of App\Exceptions\MyOwnException , you check for that instance instead.


1 Answers

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.

like image 130
jedrzej.kurylo Avatar answered Sep 20 '22 21:09

jedrzej.kurylo