简体   繁体   English

存储库应该引发自定义异常还是返回状态类型?

[英]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'. 我有一个Web应用程序和一个将交易记录设置为“完成”的存储库。 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... 存储库的调用者(一种服务)处理存储库调用,并将结果包装到DTO到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., 抛出异常并捕获它并不是更好的做法,因为无论何时发生异常,在处理异常之前,它都会为.Net框架添加一些额外的工作,以收集所有信息,例如Stacktrace,源和许多其他信息。

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. 而是具有一个响应RepositoryResponse类,如下所示,您可以填写详细信息并将其返回以在其他层中进行处理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 insert方法是应该返回一个对象还是抛出异常 - Should an insert method return an object or throw exceptions 返回 Task 的方法应该抛出异常吗? - Should methods that return Task throw exceptions? 托管代码是否应该返回错误或将异常抛给非托管代码? - Should managed code return an error or throw exceptions to unmanaged code? 自定义流可以引发自己的自定义异常,还是仅应引发IOException? - Can a custom stream throw its own custom exceptions or should it only throw IOException? 我应该返回状态代码还是在.Net Web Api 2中抛出异常 - Should I return a status code or throw an exception in .Net Web Api 2 有没有不应该抛出异常的函数? - Are there any functions that should not throw exceptions? 我应该如何从存储库返回自定义结果集? - How should I return custom result sets from repository? 如果操作返回类型是 API 中的自定义 class,如何返回状态码? - How to return status code if action return type is custom class in API? 不想引发异常,是否应该返回一个包含bool和string数组的自定义类? - Don't want to throw an exception, should I return a custom class that holds a bool and string array? 存储库是否应返回Task <SomeEntity> ? - Should a repository return Task<SomeEntity>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM