Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Cannot catch database exception in seed or migration class

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.

like image 626
eleftrik Avatar asked Feb 13 '23 10:02

eleftrik


1 Answers

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");
}
like image 149
Blue Genie Avatar answered Feb 16 '23 02:02

Blue Genie