简体   繁体   中英

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...

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; }
}

I would simply return a enum because why should you throw an exception?
There is no error appeared so there is no need for throw an exception IMHO

here a example of how it cloud look like:

public myenum RepositoryMethod()
{
   if(alreadyDone())
     return myenum.AlreadyDone;

   try
   {
       return myenum.Done;
   }
   catch(ex)
   {
       return myenum.ERROR;
   }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM