我应该如何处理每个操作都可能引发错误/异常的操作列表上的错误?

发布于 2024-10-06 08:29:36 字数 868 浏览 0 评论 0原文

我试图从必须执行的一系列操作中找出应该如何以及在哪里处理错误:

摘要:

我将一个 List 和一个 Settings 对象传递给 ProcessActions 类。 ProcessActions 类迭代字符串列表,从我的工厂获取适当的实例化对象,并对每个对象调用 object.Execute()。

class ProcessActions : IEngine
{
    public ActionFactory Factory { get; set; }
    public IList<string> Actions { get; set; }
    public ISettings Settings { get; set; }
    public ProcessActions(IList<string> actions, ISettings settings)
    {
        Factory = new ActionFactory();
        Actions = actions;
        Settings = settings;
    }

    public void Execute()
    {
        foreach (var action in Actions)
        {
            var task = Factory.CreateInstance(action, Settings);
            task.Execute();
        }
    }
}

最初,我将所有错误记录在字典中,并将其传递回调用 .Execute() 的对象。但是,我是否能够收集每个对象中抛出的任何异常并返回这些异常,以便我可以将它们记录在此 ProcessAction (某种类型的集合)中?

I am trying to figure out how and where I should handle my errors from a list of actions that I have to carry out:

Summary:

I am passing a List and a Settings object to a ProcessActions class. The ProcessActions class iterates through the list of strings and gets the appropriate instantiated object from my factory and calls the object.Execute() on each object.

class ProcessActions : IEngine
{
    public ActionFactory Factory { get; set; }
    public IList<string> Actions { get; set; }
    public ISettings Settings { get; set; }
    public ProcessActions(IList<string> actions, ISettings settings)
    {
        Factory = new ActionFactory();
        Actions = actions;
        Settings = settings;
    }

    public void Execute()
    {
        foreach (var action in Actions)
        {
            var task = Factory.CreateInstance(action, Settings);
            task.Execute();
        }
    }
}

Originally I was recording any errors in a dictionary that I pass back to the object that called .Execute(). However, would I be able to gather any thrown exceptions in each object and return those so that I could log them in this ProcessAction (some type of collection)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

翻身的咸鱼 2024-10-13 08:29:36

.NET 4 引入了 AggregateException ,这本质上就是您所要做的问。它似乎是专门为 PLINQ 和其他并行库相关对象引入的,这些对象可能有多个线程都抛出异常。就像任何其他异常一样,它是一个可抛出的对象。

看起来您没有并行执行,因此这并不完全是它的设计目的,但也许可以使用它或调整概念。请参阅参考页面的备注部分。

.NET 4 introduced the AggregateException which is essentially what you're asking. It appears as though it was introduced specifically for the PLINQ and other parallel library related objects which could have multiple threads all throwing exceptions. It's a throwable object just like any other exception.

It looks like you're not executing in parallel so this isn't quite what it was designed for but maybe it can be used or the concept adapted. See the remarks section of the referenced page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文