Laravel 5-try-catch异常不起作用


Laravel 5 - try catch exception not working

我是laravel5的新手,此代码无法捕获所有异常。我不知道怎么了,请帮帮我。

public function delete($id)
{
    $sql = $this->deleteSql();
    DB::beginTransaction();
    try {
        $deleteData = Db::delete($sql, ['id' => $id]);
        if (!$deleteData) {
            return false;
        }
        return true;
    } catch ('Exception $e) {
        DB::rollback();
        return $e->getMessage();
    }
    DB::commit();
}

它会给我:

Illuminate''Database''QueryException:SQLSTATE[22P02]:由PDO异常:SQLSTATE[22P02]:

您的方法根本不会去catch块,因为它从try块返回bool

我也不知道是什么让你使用try...catch块。

I更多错误:

Db::delete($sql, ['id' => $id]);

如果您已经定义了Db,那么它是可以的。但如果没有,那么它将抛出错误。

此外,不需要使用事务,除非您正在使用任何PHP测试工具(如phpUnit/phpSpec等)测试应用程序。


解决方案:

根本不需要使用try..catch块。

只需对要删除的模型调用delete方法,就可以完成,如下所示:

public function delete($id)
{
    YourModel::delete($id); // Replace YourModel with the model you wish to delete
    'Session::flash('delete_message', 'Model has been successfully deleted.');
    return redirect()->back(); // or anywhere else of your choice
}

希望这能帮到你。快乐编码。干杯