10

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?

3
  • Where did you put that try/catch clause? Commented Jul 20, 2015 at 6:03
  • Is this Laravel 4.2 or 5+? Commented Jul 20, 2015 at 7:48
  • 5.1. Silly me, I didn't use a backslash before the Exception class. Let me try that... Commented Jul 20, 2015 at 15:53

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah. Looks like a careless error on my part. I will try this and if it works I will choose this answer.
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.