Search code examples
c#asp.net-mvcrepository-design

Should a repository throw custom exceptions or return a status type?


I have web app and a repository that sets a transaction record to 'done'. The requirement is to check at repository level if the requirement has been set already to 'done' by another user, when so, inform the current user that the records has already been set to 'done'.

Should I throw a custom exception or return a status class (with status enum and message collection) ?

The caller of the repository (kind a service) handles the repository calls and wraps the results to a DTO to the UI...


Solution

  • Throwing an exception and catching it is not a better practise, because whenever exception occurs, before it's handled, it adds some additional work for the .Net framework to collect all the information like Stacktrace, source and lot of other information.,

    Instead have a response RepositoryResponse class as shown below and you can fill in the details and return it to handle in a different layer.

    class RepositoryResponse
    {
        public bool IsSuccess { get; set; }
    
        public string ErrorMessage { get; set; }
    }