抛出异常还是引发域事件?

时间:2022-06-06 20:17:59

Consider the following piece of code:

考虑以下代码:

public class Article : AbstractEntity<Article> {    

    // ...

    public void AppendFeedback(Feedback feedback) {
        var quota = this.FeedbacksQuota ?? this.DefaultFeedbacksQuota;            
        if(this.Feedbacks.Count >= quota) {
            throw new ApplicationException("message");
        }
        this.Feedbacks.Add(feedback);
    }

    // ...
}

So I don't know how would I notify users when quota gets exceeded. Throwing an exception seems bad to me. Is it the right place to use domain events? (Examples are appreciated, especially in context of ASP.NET MVC application).

所以我不知道当配额被超过时该如何通知用户。我觉得破例很糟糕。它是使用域事件的合适位置吗?(例子不胜枚举,特别是在ASP的背景下。净MVC应用程序)。

Where should I gather/handle the messaging?

我应该在哪里收集/处理消息?

Thanks!

谢谢!

1 个解决方案

#1


1  

If your feedback quota is an invariant (business rule) then an exception is fine.

如果您的反馈配额是不变的(业务规则),那么可以使用异常。

You can always add a method such as:

您可以添加如下方法:

public bool CanAddFeedback
{
    get { return this.Feedbacks.Count < quota; }
}

To check whether feedback is allowed before adding so that you can return a meaningful/user friendly message.

在添加之前检查是否允许反馈,以便返回有意义的/用户友好的消息。

You could raise a domain event on feedback added that contains the quota left, etc.

您可以通过添加包含剩余配额的反馈来提高域事件。

#1


1  

If your feedback quota is an invariant (business rule) then an exception is fine.

如果您的反馈配额是不变的(业务规则),那么可以使用异常。

You can always add a method such as:

您可以添加如下方法:

public bool CanAddFeedback
{
    get { return this.Feedbacks.Count < quota; }
}

To check whether feedback is allowed before adding so that you can return a meaningful/user friendly message.

在添加之前检查是否允许反馈,以便返回有意义的/用户友好的消息。

You could raise a domain event on feedback added that contains the quota left, etc.

您可以通过添加包含剩余配额的反馈来提高域事件。

相关文章