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
Any idea? Thanks for your help.
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");
}
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 (eg 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 (eg 10) or if I disable XDebug (not a good solution), everything runs ok, and inside migrations/seeds I can catch QueryExceptions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.