cakephpcakephp-2.0cakephp-2.3

cakephp - How to handle integrity constraint violation errors


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.


Solution

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