laravel - 为什么我的异常没有被 Laravel 的 destroy 方法捕获?

标签 laravel destroy

为什么我的异常没有被捕获?

    try {
        \Account::destroy($id);
        return Redirect::to("/manager/account")
                            ->with("success_message", "Item excluido com sucesso");
    } catch (Exception $e) {
        return Redirect::to("/manager/account/{$id}/edit")
                        ->with("error_message", "Erro ao excluir item");
    }

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (imob_io.users, CONSTRAINT users_account_id_foreign FOREIGN KEY (account_id) REFERENCES accounts (id)) (SQL: delete from accounts where id = 2)

最佳答案

当前您正在捕获当前命名空间内的类 Exception。相反,您应该引用全局类型 \Exception:

catch (\Exception $e){
    return Redirect::to("/manager/account/{$id}/edit")
                    ->with("error_message", "Erro ao excluir item");
}

我还建议您缩小范围,而不是只捕获每个异常。例如,您可以捕获 QueryException,它将因违反约束等而被抛出。

catch(\Illuminate\Database\QueryException $e)

关于laravel - 为什么我的异常没有被 Laravel 的 destroy 方法捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877312/

相关文章:

c# - 如何在另一个函数中访问 OnTriggerEnter2D 的值?

laravel - Laravel Blade 文件中的 {{ }} 和 {{{ }}} 有什么区别?

php - Homestead 5、Xdebug、PHP 7 和 PhpStorm

php - Blade 模板可能无法在 Laravel 4.1 中工作?

jquery - 销毁并重新创建 jQuery 数据表

ruby-on-rails - 无法销毁多对多关系中的记录

php - Foreach() 和 each() 内存不足,分块不起作用

php - Laravel 多模型关系返回计数

delphi - 在 Firemonkey 中运行时创建然后销毁 TLabels

java - Android 阻止后退按钮销毁后 Intent 恢复