【问题标题】:Why is my exception not caught by the Laravel destroy method?为什么我的异常没有被 Laravel destroy 方法捕获?
【发布时间】:2015-03-08 18:18:19
【问题描述】:

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

    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]:违反完整性约束:1451 无法删除或 更新父行:外键约束失败 (imob_io.users,约束users_account_id_foreign外键 (account_id) 参考accounts (id)) (SQL: 删除 accounts 其中id = 2)

【问题讨论】:

  • 尝试捕获\Exception 而不是Exception
  • 哎哟....!!命名空间!!谢谢

标签: laravel destroy


【解决方案1】:

目前,您正在当前命名空间中捕获 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)

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 2012-01-22
    • 1970-01-01
    • 2020-11-16
    • 2010-11-25
    • 2012-02-24
    • 2017-06-18
    相关资源
    最近更新 更多