CodeIgniter Forums

Full Version: Catching database errors?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Tim Stackhouse[/eluser]
I'm trying to figure out how to catch and respond to database constraint errors, here's the deal:

I have a table 'role' it has a primary key of 'id'.
I have another table 'user_role' it has a 'FOREIGN KEY (role_id) REFERENCES role(id) ON DELETE RESTRICT'

This is the behaviour I want, I don't want to be able to delete a role if I have users assigned that role, however it's producing this wonderfully ugly database error, how can I trap that error and handle it more gracefully?

El Forum

[eluser]Tim Stackhouse[/eluser]
No thoughts on this? Is there no way to catch this in CI?

El Forum

[eluser]TheFuzzy0ne[/eluser]
I don't think it's possible without overriding the display_error() method in the DB_driver class. http://codeigniter.com/wiki/Extending_Database_Drivers/

El Forum

[eluser]Tim Stackhouse[/eluser]
I did some searching and found this thread: http://ellislab.com/forums/viewthread/79950/ and that will work nicely, it's because I'm in development mode.

El Forum

[eluser]TheFuzzy0ne[/eluser]
Sorry, I didn't realise you wanted to just hide the errors, I thought you wanted to "trap that error and handle it more gracefully". Smile

El Forum

[eluser]Tim Stackhouse[/eluser]
Well, it's a combination of the two, I can suppress the error by turning off debugging and handle the error internally, either showing a message that they can't do it because of the foreign key or if it's a more serious error, blowing up more gracefully.