【问题标题】:Create a method which catches exception if occurred in any of the methods in that class in c#如果在 c# 中该类的任何方法中发生异常,则创建一个捕获异常的方法
【发布时间】:2019-07-09 12:09:02
【问题描述】:

我有一个类Demo,它有以下四种方法Add()Update()Delete()Get()

这些方法如下链接在一起:

bool isSuccess = this.Get(1)
                    .Update(200) //new product price

现在,我想实现CatchError() 方法,该方法将捕获上述任何方法中发生的Exception if

代码如下所示:

bool isSuccess = this.Get(1)
                    .Update(200); //new product price
                    .CatchError();

我有no idea如何实现CatchError()方法。

很乐意提供更多信息以帮助正确回答问题。

【问题讨论】:

  • 创建CatchError() 方法是否是一种解决方案,其中您有一个action/Func 参数。参数为 this.Get(1).Update(200) 。该参数看起来就像@JeroenMostert 在下一条评论中写的那样。 --> () => this.Get(1).Update(200)
  • 您不能将其实现为方法上的链。但是,您可以实现一个包装Action 的方法,因此您可以将() => this.Get(1).Update(200) 传递给它。 (虽然从技术上讲,您可以将这样的Action 与扩展方法链接起来,但这些往往比他们澄清的更多。)
  • 所有方法(GetUpdate 等)返回什么?
  • 你为什么不this.SubscribeOnError(Class_OnError).Get(1).Update(200); 这样你只需要在方法中提出一个CancelEventHandler 如果他们给出错误。
  • 添加了一个没有事件的答案,但只是调用函数@BijayYadav

标签: c# .net try-catch method-chaining


【解决方案1】:

就像我在评论中写的那样,我会尝试创建一个 CatchError() 方法,您可以在其中将 Action 作为参数:

bool isSuccess = CatchError(() => Get(1).Update(200));

您的 CatchError() 方法如下所示:

private static bool CatchError(Action action)
{
    try
    {
        action();
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

【讨论】:

  • 在进一步的旁注中,并不是关于问题所问的实际问题(因此,实际上只是旁注):除非应该处理令人烦恼的异常,否则捕获异常并完全忽略异常信息及其指示的异常情况/问题通常不是一个好主意,因为这样会丢失/忽略在解决程序/软件问题时可能非常有用或完全必要的信息......
  • 没错。所以如果有人使用这段代码,异常处理应该在catch中进行。这意味着他应该记录它,或者将它展示给用户。但我只想展示一个使用方法捕获异常的机会。
【解决方案2】:

要实现这一点,您应该仅在调用 CatchError 时执行所有操作。到此为止,您应该收集所有必须执行的操作。 比如:

public class Demo
{
    private int Value;
    private List<Action> Operations = new List<Action>();
    public Demo Get(int a)
    {
        this.Operations.Add(() => this.Value = a);
        return this;
    }

    public Demo Update(int a)
    {
        this.Operations.Add(() => this.Value += a);
        return this;
    }

    public bool CatchError()
    {
        foreach (var operation in Operations)
        {
            try
            {
                operation();
            }
            catch (Exception e)
            {
                return false;
            }
        }
        Operations.Clear();
        return true;
    }
}

【讨论】:

  • 是的,但是如果提问者(或其他人)编写像someDemo.Update(...); 这样的代码而不附加CatchError() 怎么办?这种方法很容易导致编写的代码不符合您在查看代码时所期望的那样......
  • 恕我直言,流畅的 API 应该在调用方法时执行操作。
  • @elgonzo 这取决于应该如何使用整个构造。如果要使用构建器模式,我们最后会调用一些“构建”方法,它可能是 BuildAndCatchError。重要的是要知道这些操作到底在做什么以及应该如何访问结果。
  • @MaksimSimkin,我同意问题中给出的方法名称所暗示的含义。您的答案可能非常适合不同的情况,但就我们从问题中了解到的情况而言,它并不适合...
【解决方案3】:

如果您在 fluent API 中创建一个方法来捕获异常,您还需要决定是否要继续执行 fluent 调用。代码如下。

如果不需要创建流畅的方法,我建议Presis's answer,因为它不太复杂。

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        bool processCancelled = false;
        myCar.SubscribeOnError(CarOnError).Paint(ref processCancelled, "red").Sell(ref processCancelled, 25000d);
    }

    public static bool CarOnError(Exception e)
    {
        // Log exception
        // Decide if must cancel
        return true;
    }
}

public class Car
{
    private Func<Exception, bool> onErrorMethod = null;

    public Car SubscribeOnError(Func<Exception, bool> methodToCall)
    {
        onErrorMethod = methodToCall;
        return this;
    }
    public Car Paint(ref bool cancelled, string color)
    {
        if (cancelled) return this;
        try
        {
            // Do stuff
        }
        catch (Exception exc)
        {
            cancelled = onErrorMethod == null ? true : onErrorMethod(exc);
        }
        return this;
    }
    public Car Sell(ref bool cancelled, double price)
    {
        if (cancelled) return this;
        try
        {
            // Do stuff
        }
        catch (Exception exc)
        {
            cancelled = onErrorMethod == null ? true : onErrorMethod(exc);
        }
        return this;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2015-11-13
    • 2013-08-13
    相关资源
    最近更新 更多