Skip to content
Advertisement

get the id from an exception message spring boot

hello guys i hope you’re doing well, I’m catching an exception (DataIntegrityViolationException) where the specified id can’t be deleted because it’s still in the parent entity. I want to know if there is any way to get that specified id from the caught exception.

Advertisement

Answer

DataIntegrityViolationException just wraps the exception thrown by the underlying JDBC driver. So it depends on if the JDBC driver provides such information in the thrown exception. But from my experience , most of the JDBC drivers will not provide the violated ID directly from the exception. It just provides some kind of error code or error message. You can try to see if it can and make sense to parse the violated ID from it.

A more reliable way to find the violated ID is to check it by yourself according to your business domain before deleting rather than relies on the thrown exception. In this case, you can simply find out if there are parent exist for the children entity before actually deleting it.

To get the exception thrown by the JDBC driver from DataIntegrityViolationException (i.e root cause exception), I tend to use the Guava library to get it.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement