0
Speak devs, all right?
How best to deal with duplicity errors when trying to create field with Constraint Unique?
Just let the exception happen? Or I a findByAlgumCampo and if it already exists I do not save(..) ?
0
Speak devs, all right?
How best to deal with duplicity errors when trying to create field with Constraint Unique?
Just let the exception happen? Or I a findByAlgumCampo and if it already exists I do not save(..) ?
1
Oops, all right and so on?
So it all depends on the business rule of your application. But I believe that if you do the find
before and did not execute the save(...)
, you will have to report some error to the user saying that the data was not saved by already existing.
So in that sense, I believe it’s best to leave the exception
happen, but treat it at the time of displaying to the user (or return in the API).
In the case of the API, it is important that the bank error is not returned directly, but that you treat it, and return a more "generic":
{
"erro": "O registro já existe"
}
But as I said there, it all depends on the business rule of the application, and the scenario in question.
Something like that.
Browser other questions tagged java postgresql spring jpa
You are not signed in. Login or sign up in order to post.
Without more information the scenario becomes difficult to answer, it will be "based on opinions". If this happens rarely, since you have the Constraint in the bank, let it fail, put the code in a Try/catch and ready. If it happens frequently, it might make more sense to validate first. The best strategy depends on the query, if the table is small and can use cache, many variables. At first let give error, treat and use a log, depending on the results (many errors, etc) can change in the future
– Ricardo Pontual
the idea was to leave it generic because I wanted to know if there was any pattern to be followed. however, later I discovered that the exception is more generic than I would like and requires the same amount of code (if not more) to identify that it was of type 'duplicity''.
– Willams S. de Sousa
in general database access providers return more specific errors in Constraint cases, look at this. Validating before also means doing two operations on the database, select and Insert. As I commented on the question, have a good look at your case, but the simplest is to let give Exception and treat
– Ricardo Pontual