2014-01-23 54 views
2

在这里是一片迷茫。我需要知道如何处理完整性约束违规情况下的错误消息。cakephp - 如何处理完整性约束违规错误

意思是我想向用户展示,而不是显示像

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

我需要捕获这些DATABSE错误,只显示消息好像说

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

我们如何处理错误消息的一些有意义的信息这个。

我已经找到了refernce这里:https://stackoverflow.com/a/8842963/576523

,但我不想做一个计数检查。

当我们使用debug_kit插件中我们可以看到,他们已抓获了

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

Thankz。

回答

6

你也可以使用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

Thankz man ...哇这真的很简单!我整天都在搜索这个......应该有更聪明的想法...... –

+0

如果你使用的是CakePHP 3,那么正确的是@Faisal anwser。 – tiagoa

2

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

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