I'm studying CQRS and FluentValidations and I found myself wondering where would be the best place to validate information within the database: directly in the handlers responsible for orchestrating the requests or within the validations even before reaching the handlers?
I have a business rule that involves the identity of an entity, where in the database this attribute is a unique key, that is, this document can only be linked to a single record. If the document already exists in the database and there is an attempt to insert it again, the database will return an error of contraint violated and I don't want that to happen, I want to handle as few exceptions as possible coming directly from the database.
So, I want to create a rule that validates at the time of insertion if the document in question is already linked to another entity and if it is already I will return an error stating that it is already linked to a record.
I managed to do this validation both ways. The first way was to validate this document directly in the handler, where I research if it is already linked to a record in the database, if it is, I return the error. The second way was to add a dependency injection inside the class that does the validations using FluentValidation.
So, my question is, what is the recommended practice for this situation?