问题
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.
回答1:
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);
}
回答2:
Using CAKEPHP3 -> CakePHP 3 - Catch Error
try
{}
catch (\PDOException $e)
{}
Solved like a charm ;) - \Exception or \PDOException
回答3:
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';
//exact error message $e->getMessage();
}
来源:https://stackoverflow.com/questions/21300127/cakephp-how-to-handle-integrity-constraint-violation-errors