I've got the following:
Clientside C# application. Contains forms for CRUD operations. It uses an API for all data operations. Input is validated on the client, and obviously also on the server (API).
I use the repository pattern for calling my API. That's because I want to communicate with data layers via interfaces, and want to be able to have multiple data sources for one repository interface. Like:
ICustomerRepository
- bool CreateCustomer(Customer customer);
- Customer GetCustomer(int id);
- bool UpdateCustomer(Customer customer);
- bool DeleteCustomer(int id);
APICustomerRepository : ICustomerRepository
DatabaseCustomerRepository : ICustomerRepository
So far the context of the question.
When the API is called by the client, and a validation error would occur (or maybe some server error that is put in the response data), the errors have to be handled on the client.
API responses are JSON, and when it's an error response, it's a JSON structure like {name: "Name is required"}
.
The point is: what is the best approach to give those errors back to the code that uses my repository classes.
As you can see, I return boolean values from repository methods which indicate success/failure.
I would like to not just return a success/fail bool, but the actual errors that came via the API response.
So, I could change the design and modify the method signatures to return a collection of errors. But the problem is, that 'read' operations like GetCustomer(int id)
already need their return value to return the actual data on success. The return value of the method cannot be used for error handling anymore.
Solutions I can think of:
Throw exceptions for everything. But this seems ugly. Because in my understanding there's a distinction between exceptional errors (like no internet connection while calling API, or API server is down), and non exceptional errors (like just wrong input that somehow slipped through the clientside input validation). Although the non-exceptional errors I mention are rare, and would theoretically never occur on the serverside validation.
Wrapping the data (return value) of repository methods in a wrapper object, that can also contain a collection of error messages.
After API response that indicates failure (and thus contains the error messages), save the messages in a class property of the repository class, and the code thet uses the repository has to check explicitly if there are errors stored in that class. (Seems to be ugly too).
What's the best or most common approach?