【问题标题】:Java - Avoid pattern duplicationJava - 避免模式重复
【发布时间】:2020-08-26 18:52:51
【问题描述】:

Java 在我的服务器代码中,对于每种方法,我都必须执行以下操作

    @Path("...")
    public Response function(...) {
        try {
            result = do some work to get result
            log the result
            return result
        } catch (Exception e) {
            log error
            return error
        }
    }

我将不得不在任何地方复制这种模式,并且只为新端点更改 do some work to get result 部分。

有什么方法可以减少重复吗?

附: do some work to get result 可以很像获取 Json 文件,或者访问多个数据库并计算结果,需要在 try-catch 块中。

【问题讨论】:

  • 将您的异常映射到未经检查的异常,然后就不需要尝试捕获了!不是这个的粉丝。但是 Spring Framework 或 Hibernate 没有某种方式可以做类似的事情吗? stackoverflow.com/questions/29851253/…oracle.com/technical-resources/articles/enterprise-architecture/…
  • @JGFMK 但这不允许您在发生异常时返回特定(即基于请求)错误响应
  • 每个函数的异常处理是相同的还是不同的?
  • 所有函数的异常处理都是一样的
  • @JGFMK 谢谢,看起来我应该看看

标签: java design-patterns


【解决方案1】:

您可以创建如下所示的函数:

  public static <T> T doTheThing(Supplier<T> supp, Supplier<T> errorSupp) {
    try {
      T result = supp.get();
      //log the result
      return result;
    } catch (Exception e) {
      //log error
      return errorSupp.get();
    }
  }

然后您可以将 a) 实际工作和 b) 潜在错误的供应商传递给此函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2022-01-23
    • 2021-11-07
    相关资源
    最近更新 更多