I have a database with a table categories which has a unique key on item_id and user_id. When I’m adding new categories in my controller it using:
$category = new Model_Category();
$category->item_id = $item_id;
$category->user_id = $user_id;
$category->save();
Kohana 3.2 returns a “Duplicate entry ‘1-3’ for key” error. Is it better practice to wrap it in a try/catch or would it be better to check whether the unique key already exists before trying to add it?
I would advice on a try catch, since it uses one less query to check for the duplicate key, however that might limit the amount of information you can display to the user since im not sure if the exception contains the actual column that violates the key, i think its just a generic error so if you want to actually check which of the two columns gives the error you might wanna use a query before that. Hope it helps. FYI i use try catch most of the time, its cleaner and easy to log errors.