【问题标题】:how to continue the program when there is exception while calling feign client api in java在java中调用feign客户端api出现异常时如何继续程序
【发布时间】:2021-08-03 23:40:44
【问题描述】:
public string prospect(List<ProspectRequest> prospectRequest, String primaryClientId) {
    if(p2p(primaryClientId)=="Success") {
        for(ProspectRequest prospect : prospectRequest) {
            p2p(prospect.getId());
       }
   // rest of code i would like to continue
    }
 }

public string p2p(String id){
crmApi.getProspectId(id);//this is external client api
String message = "Success"; 
return message;
}

如果 p2p(primaryClientId) 失败,那么我需要停止整个过程。我如何继续“我想继续的其余代码”。

如果 feign 客户端 api crmApi.getProspectId 成功,则返回成功消息,这是一个很好的案例。 如果 crmApi.getProspectId api 给出错误,那么我仍然需要为下一组客户端继续 p2p() 程序。它是如何工作的。

提前致谢。

【问题讨论】:

  • BTW == 字符串看起来很不Java。 “succes“.equals(p2p(…)) 将确保它适用于非实习字符串。

标签: java spring-boot rest java-8 feign


【解决方案1】:

好像你只需要使用 try catch finally 块

  public string prospect(List<ProspectRequest> prospectRequest, String primaryClientId) {
  

    try {
      if(p2p(primaryClientId)=="Success") {
         for(ProspectRequest prospect : prospectRequest) {
            p2p(prospect.getId());
        }
    } catch (RuntimeException e) {}  // Exception can be specified exp. RuntimeException
    finally {
       // rest of code i would like to continue
    }
    }
 }

public string p2p(String id){
crmApi.getProspectId(id);//this is external client api
String message = "Success"; 
return message;
}

如果你需要第一个 if 块之外的东西,你可以在 catch 块中放置一个选项(如果 if 块失败)。当

if(p2p(primaryClientId)=="Success") {
             for(ProspectRequest prospect : prospectRequest) {
                p2p(prospect.getId());
            }

抛出一个检查异常,你需要将 RuntimeExpection 更改为超类 Exception

编辑:

 for(ProspectRequest prospect : prospectRequest) {
      try {
        p2p(prospect.getId());

} 捕捉 (RuntimeExpection e) {} }

【讨论】:

  • 嘿 Marlos 感谢您的回答。我还有一个问题 - 假设我的前景请求列表中有 3 个对象,我需要对每个对象执行 p2p() 操作。假设第二个对象在 p2p 方法中遇到来自第三方客户端的错误。如果停在那里,我需要继续下一个对象。我该如何解决这个问题?
  • 您可以围绕操作创建第二个 try-catch 块,甚至只围绕该操作创建。我已经编辑了我的原始答案。
猜你喜欢
  • 2019-04-21
  • 2018-07-06
  • 2019-02-18
  • 2019-07-27
  • 1970-01-01
  • 2020-05-05
  • 2020-07-25
  • 2012-03-08
  • 1970-01-01
相关资源
最近更新 更多