Here I see two questions, and here is my take ...
Are database restrictions good? For large systems, they are indispensable. Most large systems have more than one interface, and are not always compatible languages ββwhere mid-level data logic or UI can be shared. They can also have batch processes only in Transact-SQL or PL / SQL. This is good to duplicate front-side validation, but in a multi-user application, the only way to really verify uniqueness is to insert a record and see what the database says. The same with foreign key constraints - you really don't know until you try to insert / update / delete.
If exceptions are allowed to throw or need to return values? Here's the code from the question:
try { // inset data } catch (SqlException ex) { if (ex.Message.ToLower().Contains("duplicate key")) { if (ex.Message.ToLower().Contains("url")) { return 1; // Sure, that one good way to do it } if (ex.Message.ToLower().Contains("email")) { return 2; // Sure, that one good way to do it } } return 3; // EVIL! Or at least quasi-evil :) }
If you can guarantee that the calling program will actually act on the basis of the return value, I think that return 1 and return 2 best left to your discretion. I prefer to rebuild a custom exception for such cases (like DuplicateEmailException ), but only me - return values ββwill do the trick too. After all, consumer classes can ignore exceptions as easily as they can ignore return values.
I am against return 3 . This means an unexpected exception (database down, bad connection, whatever). Here you have a vague error, and the only diagnostic information you have is: "3". Imagine a SO question that says I tried to insert a line, but the system said "3". Please advise. It will be closed in a few seconds :)
If you do not know how to handle an exception in a data class, there is no way that the consumer of the data class can handle it. At the moment, you have a lot of moves, so I say, I register an error, and then I exit as gracefully as possible with the message "Unexpected error".
I know a little to tell about the unexpected exception, but I handled too many support incidents, when the programmer just looked for database exceptions, and when something unexpected appeared, the application either failed or failed down, leaving zero diagnostic information. Very naughty .