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

时间:2014-01-23 05:30:47

标签: cakephp cakephp-2.0 cakephp-2.3

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

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

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

我需要捕获这些数据库错误并只显示像

这样的消息
The item you are trying to delete is associated with other records 

我们如何处理这个问题。

我在这里找到了推荐:https://stackoverflow.com/a/8842963/576523

但我不想做计数检查。

当我们使用debug_kit插件时,我们可以看到他们已经在

下捕获了这些值

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

Thankz。

3 个答案:

答案 0 :(得分:7)

您也可以使用try - catch

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);
}

答案 1 :(得分:4)

使用CAKEPHP3 - > CakePHP 3 - Catch Error

str = str.replace(/\W+/g, '-').replace(/\-$/, '').toLowerCase();

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

答案 2 :(得分:4)

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

try {
    $this->Item->delete();
} catch (\PDOException $e) {
    $error = 'The item you are trying to delete is associated with other records';
    //exact error message $e->getMessage();
}
相关问题