In my project, I have a service layer that manipulates repositories. The service layer is called by my controllers.
In many cases, my controller layer is able to validate incoming information before it gets any further into the system. In some cases however, errors may arise due to submitted data not being valid, but only at a point that is within my service layer.
With that in mind, let's assume I'm doing a user signup flow:
- Duplicate usernames are not allowed
- The username can be provided
- If the username is not provided, it is generated from the first and last name
This means that the process of generating (if necessary) and checking for duplicate usernames transpires in the service layer.
In the event of a duplicate, what is the most decoupled and ideal way for me to signal back to the caller (be it a controller, a background task, or even another service) - that:
- There is a problem with the username field
- Where applicable, the username that was generated
Ideally the approach suggested would be able to apply to errors that happen in other services so that I can come up with a consistent way to report and thus handle errors in calling layers.