cakephp - How to handle integrity constraint viola

2019-02-25 05:53发布

Am at a loss here. I need to know how to handle error messages in case of integrity constraint violations.

Meaning i want to show users some meaningful message instead displaying error messages like

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

I need to capture these databse errors and just show messages like say

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

How do we deal with this.

i have found a refernce here : https://stackoverflow.com/a/8842963/576523

but i dont want to do a count check.

When we use the debug_kit plugin we can see that they have captured these values under the

variables tab. I need a way to do this or access these data from the debug_kit plugin.

Thankz.

3条回答
成全新的幸福
2楼-- · 2019-02-25 06:36

If you only want to catch a specific exception, specify the exception class in the catch block.Hope it will solve your problem.

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();
}
查看更多
老娘就宠你
3楼-- · 2019-02-25 06:41

Using CAKEPHP3 -> CakePHP 3 - Catch Error

try
{}
catch (\PDOException $e)
{}

Solved like a charm ;) - \Exception or \PDOException

查看更多
别忘想泡老子
4楼-- · 2019-02-25 06:48

You could also use 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);
}
查看更多
登录 后发表回答