【问题标题】:How to create a generic try catch repeated code?如何创建通用的 try catch 重复代码?
【发布时间】:2020-06-08 11:52:03
【问题描述】:

几乎我所有的 C# 代码都是这样的:

try
{
   response = SomeMethod(requestModel);
}
catch (Exception ex)
{
  this.logger.Log(ex.MoreDetails());
  response = this.BadRequest();
}

SomeMethod 是唯一不同的东西,但所有请求模型都继承了一些父模型。 有什么提示,所以我不必在所有代码上重复这个吗?响应也使用相同的通用模型。

【问题讨论】:

  • 看看这个答案,您应该为此定义一个基类并实现该功能。或者只是一个带有委托的静态方法。 stackoverflow.com/a/2139878/13583842
  • 您可以编写一个辅助方法,该方法接受 Func<Request> 并为您执行 try catch 和日志记录。
  • 如果您的所有代码真的只有这些,那么只需处理 SomeMethod 中的异常并在必要时返回 BadRequest

标签: c# generics try-catch


【解决方案1】:

您可以创建一个接受Func 作为参数的方法:

class Request{} 
class BadRequest:Request{}
class AnotherRequest:Request{}

static Request HandleException(Func<Request> f)
{
    Request result ;
    try
    {
        result = f();
    }
    catch (Exception ex)
    {
        result = new BadRequest();
    }
    return result;
}

static AnotherRequest SomeMethod(int i) => new AnotherRequest();  

及用法:

Request result = HandleException(() => SomeMethod(1));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2011-08-03
    • 1970-01-01
    • 2018-03-04
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多