Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top