How to handle duplicate key exception ?
Application Type

Hello, we want to handle the duplicate key exception to show a more user-friendly message to the end user rather than the raw exception message.

Other than testing for the presence of "Cannot insert duplicate key" in the error message, is there an error handler for specific database exceptions ? 

We'd like also to handle FK protection exception on deletes. 

Can this help you?

It has some answers that might help you, in this case the post's solution says to handler with the database exception handler, but you can have a look on the link.

For the fk you can use the delete rules: protect, ignore and delete.

Have a look at the link below.

But, if you want to validate before trying to create or update your table or tables you always need to validate if is possible to delete something before deleting.

Kind regards,


That's the solution we're implementing, but would rather be able to handle specific database exceptions with the right database exception handler, not the generic one. Sadly, those specific db exception handlers don't exist, and we'll have to inspect the error messages to handle them properly.

So you need to do it manually as Dorine said and validate if is possible to execute what you are trying to change.

Hi François,

Afaik, all database exceptions are raised as the same exception type, so for handling it after the fact, you are condemned to trying to extract relevant information from the error message.

I prefer to avoid these exceptions before they happen by validating the intended change to the database before executing it.  At that time you know what is wrong and you can give appropriate message.


Hi Dorine, 

Was afraid that would be our only recourse, but we'll still have to go that way for some cases. 

We can't inspect every referenced table to check all the FK's to see if we can safely delete a value; handling the exception is the only reasonably feasible solution so far... 

So yes, I can see 2 reasons not to check everything : - the amount of extra code to write and maintain

- the performance penalty of all those checks being executed on every update.

If you have the budget to make a nice generic solution, I could imagine some hybrid approach where you let the database exception go off, and only in the exception handler execute the checks to avoid performance penalty in the happy flow.  And make use of the metamodel to execute the validations instead of coding them out, to avoid the burden of coding and maintaining the validations.


Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.