cakephp - 如何处理完整性约束违规错误

问题描述 投票:3回答:3

我在这里不知所措。我需要知道在违反完整性约束的情况下如何处理错误消息。

意思是我想向用户显示一些有意义的消息,而不是显示错误消息

Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

我需要捕获这些数据库错误,只显示像say这样的消息

The item you are trying to delete is associated with other records 

我们如何处理这个问题。

我在这里找到了一个参考:qazxsw poi

但我不想做计数检查。

当我们使用debug_kit插件时,我们可以看到他们已经在下面捕获了这些值

变量选项卡。我需要一种方法来执行此操作或从debug_kit插件访问这些数据。

Thankz。

cakephp cakephp-2.0 cakephp-2.3
3个回答
7
投票

你也可以使用https://stackoverflow.com/a/8842963/576523 - try

catch

4
投票

使用CAKEPHP 3 - > qazxsw poi

try {
    $this->Item->delete();
} catch (Exception $e) {
    $error = 'The item you are trying to delete is associated with other records';
    // The exact error message is $e->getMessage();
    $this->set('error', $error);
}

像魅力一样解决;) - \ Exception或\ PDOException


4
投票

如果您只想捕获特定的异常,请在catch块中指定异常类。希望它能解决您的问题。

CakePHP 3 - Catch Error
© www.soinside.com 2019 - 2024. All rights reserved.