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?
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 ) { // ... }
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With