如何在多种方法中很好地使用 try catch? [英] How to use try catch nicely in multiple methods?

查看:37
本文介绍了如何在多种方法中很好地使用 try catch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果我的问题很愚蠢,但我有这种代码:

Sorry if my question is stupid, but I have this kind of code :

public Object1 Method1(Object2 parameter)
{
    try
    {
        return this.linkToMyServer.Method1(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

public Object3 Method2(Object4 parameter)
{
    try
    {
        return this.linkToMyServer.Method2(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

/* ... */

public ObjectXX Method50(ObjectXY parameter)
{
    try
    {
        return this.linkToMyServer.Method50(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

我想你看到了模式.有没有一种很好的方法来只使用一个 try catch 并在这个 try catch 中传递一个通用方法?

I think you see the pattern. Is there a nice way to have only one try catch and to pass a generic method in this try catch ?

本能地我会使用委托,但委托必须具有相同的签名,对吗?

Instinctively I'd use a delegate, but delegates have to have the same signature right ?

提前致谢.

问候.

推荐答案

当你看到这样的代码时,你可以应用 模板方法模式.

Whenever you see code like this you can apply Template Method Pattern.

可能是这样的:

private TResult ExecuteWithExceptionHandling<TParam, TResult>(TParam parameter, Func<TParam, TResult> func)
{
    try
    {
        return func(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }
    return default(TResult);
}

public Object1 Method1(Object2 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method1);
}

public Object3 Method2(Object4 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method2);
}

等等...

这篇关于如何在多种方法中很好地使用 try catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆