使用消息类静态方法接受操作来包装 Try/Catch

发布于 2024-08-28 05:34:38 字数 948 浏览 4 评论 0原文

我有一个 Result 对象,它允许我传递事件消息列表,并且我可以检查操作是否成功。

我意识到我已经在很多地方编写了这段代码

Result result;

try
{
    //Do Something 
    ...

    //New result is automatically a success for not having any errors in it
    result = new Result(); 
}
catch (Exception exception)
{
    //Extension method that returns a Result from the exception
    result = exception.ToResult();
}

if(result.Success) ....

我正在考虑将这种用法替换为

public static Result CatchException(Action action)
{
    try
    {
        action();
        return new Result();
    }
    catch (Exception exception)
    {
        return exception.ToResult();
    }
}

然后使用它就像

var result = Result.CatchException(() => _model.Save(something));

有人觉得这有什么问题或者我正在用可重用性换取晦涩难懂吗?

编辑:我捕获所有异常的原因是我在与模型交互的任何时候都在 ViewPresenter 类中使用此代码,因为如果我收到未处理的异常,我宁愿将实际错误显示给用户(内部应用程序),而不是仅仅将他们重定向到通用错误页面。

I have a Result object that lets me pass around a List of event messages and I can check whether an action was successful or not.

I've realized I've written this code in alot of places

Result result;

try
{
    //Do Something 
    ...

    //New result is automatically a success for not having any errors in it
    result = new Result(); 
}
catch (Exception exception)
{
    //Extension method that returns a Result from the exception
    result = exception.ToResult();
}

if(result.Success) ....

What I'm considering is replacing this usage with

public static Result CatchException(Action action)
{
    try
    {
        action();
        return new Result();
    }
    catch (Exception exception)
    {
        return exception.ToResult();
    }
}

And then use it like

var result = Result.CatchException(() => _model.Save(something));

Does anyone feel there's anything wrong with this or that I'm trading reusability for obscurity?

Edit: The reason I am trapping all exceptions is I use this code inside of my ViewPresenter classes at any point I interact with my model since if I get an unhandled exception I'd rather display the actual error to the user (internal app) as opposed to just redirecting them the generic error page.

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

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

发布评论

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

评论(3

迷路的信 2024-09-04 05:34:38

我认为使用函数式方法并传入 lambda 没有任何问题。这是完全正确的。

话虽这么说,我会质疑你在这个特定场景中的使用。将所有异常捕获到通用“Result”类中似乎很危险。理想情况下,您应该捕获可以正确处理的异常 - 不是所有可能的异常并继续。

话虽这么说,如果你真的想这样做,我有几个建议给你:

1)我会为成功创建一个静态的、不可变的结果,然后这样做:

result = result.Success;

这可以避免每次你生成一个新的“成功”。成功,这希望是最常见的选择。

2)我可能会避免使用扩展方法,并且这样做:

result = new Result(exception);

这在意图上会更加清晰和明显,并且在这种情况下确实没有理由执行扩展方法......

I don't think there is anything wrong with using a functional approach, and passing in a lambda. That is perfectly valid.

That being said, I'd question your use in this specific scenario. Trapping all exceptions into a general purpose "Result" class seems dangerous. Ideally, you should be catching exceptions which you can handle correctly - not every possible exception and continuing.

That being said, if you really want to do this, I have a couple of suggestions for you:

1) I'd make a static, immutable result for success, and just do:

result = result.Success;

This avoids generating a new "success" each time you succeed, which hopefully is the most common option.

2) I'd probably avoid the extension method, and do:

result = new Result(exception);

This will be much more clear and obvious in intent, and there's really no reason to do an extension method in this case...

夜深人未静 2024-09-04 05:34:38

您不应该像这样捕获Exception。您应该只捕获您知道如何处理的已知异常类型。

如果这样做,您的代码将不再如此重复,因此就没有必要使用此模式来实现可重用性。

总的来说,这看起来是一个非常糟糕的主意,不仅仅是 lambda 模式,我正在谈论通过将异常转换为结果对象来处理异常。您基本上是在允许自己忽略所有异常并继续工作。 C# 错误处理使用异常而不是返回代码是有原因的,这是因为异常允许结构化、分层和基于调用堆栈的处理。除非您简化了这个问题的代码,否则我会重新考虑您的异常处理过程。


但总的来说,我认为 lambda 模式没有任何问题。我自己使用类似的方法来包装代码块的多次重试。但在这种情况下,我认为这不是你所需要的。

You shouldn't be catching Exception like this. You should only be catching known exception types that you know how to handle.

If you did that, you code would no longer be so repetitive, so there would be no case for using this pattern for re-usability.

All round this looks like a very bad idea, not just the lambda pattern, I'm talking about the handling of exceptions by converting them into results objects. You are basically allowing yourself to ignore all exceptions and continue working. There is a reason why C# error handling is done with exceptions and not with return codes, and that is because exceptions allow for structured, hierarchical and call stack based handling. Unless you have simplified the code for this question, I would reconsider your exception handling process.


In general though, I don't see anything wrong with the lambda pattern. I use something similar myself for wrapping multiple retries of a code block. But in this case I don't think it's what you need.

抽个烟儿 2024-09-04 05:34:38

如果您觉得需要编写这样一个自动异常处理程序系统,您可能会过度使用异常,这可能会产生严重的性能影响。

然而,这似乎是一个将异常转换为错误代码的通用系统 - 那么为什么不首先使用错误代码呢?或者学习更有效地使用异常,这样您就不需要将它们转换为错误代码?事实上,你试图将它们转换成其他东西,这应该引起你的警惕,并表明你在某个地方错过了重点。

If you feel the need to write such an automated exception handler system you may be over-using exceptions, which could have serious performance implications.

However, this appears to be a generic system for converting exceptions into error codes - so why not just use error codes in the first place? Or learn to use exceptions more effectively so you don't feel the need to convert them into error codes? The fact that you are trying to convert them to something else should raise alarms and suggest to you that you're missing the point somewhere.

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