4

Laravel 4 with MySql db. For some reason, I cannot catch DB exceptions (Illuminate\Database\QueryException) inside a seed or migration class: the code never enters the catch block.

For example, if I try to insert on a table where the column 'name' is UNIQUE:

try {
    $data = array('id' => 1, 'name' => 'foo');
    DB::table('table')->insert($data);
}
catch (\Exception $e) {
    $this->command->error("SQL Error: " . $e->getMessage() . "\n");
}

...I always get this error:

PHP Warning: Uncaught exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  • I tried to catch Exception, \Exception, \PDOException, \Illuminate\Database\QueryException and so on, but I had no luck.
  • I can catch other types of exceptions (e.g. Division by zero, etc.)
  • I can catch QueryException inside routes.php, the same code works well: code enters the 'catch', I get the message "SQL Error: etc." but no warning is raised (correct)

Any idea? Thanks for your help.

1
  • A note: same code (same GIT project) running on a Windows machine (WAMP) works correctly (I can catch the exception); running on a Mac (MAMP) id doesn't work. What's wrong? Commented Jul 11, 2014 at 11:06

2 Answers 2

7

You must catch "Illuminate\Database\QueryException"

try {
    $data = array('id' => 1, 'name' => 'foo');
    DB::table('table')->insert($data);
}
catch (\Illuminate\Database\QueryException $e) {
    $this->command->error("SQL Error: " . $e->getMessage() . "\n");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Aladin. Unfortunately it didn't work, I got "PHP Warning... SQL Exception etc.", the exception isn't catched.
1

Thanks to php exceeds execution time on throwing an exception in recursion I finally understood the problem.

Apparently it's related to XDebug, and it occurs only on PHP on Mac OS X (I tried several PHPs on Windows, but never ran into this problem), and only when running a migration or seed by CLI (e.g. php artisan db:seed --class=className).

It's related to these XDebug settings:

xdebug.var_display_max_depth = -1
xdebug.var_display_max_children = -1
xdebug.var_display_max_data = -1

I don't exactly know why, but this caused QueryException to never be catched, and PHP showed me the entire exception stack.

If I comment these options, or set them to a more appropriate value (e. g. 10) or if I disable XDebug (not a good solution), everything runs ok, and inside migrations/seeds I can catch QueryExceptions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.