【问题标题】:Spring HttpClientErrorException and RestClientException getting request URLSpring HttpClientErrorException 和 RestClientException 获取请求 URL
【发布时间】:2021-02-23 10:26:01
【问题描述】:

我在 try-catch 块中有超过 1 个 http 调用,例如:

try {
    HttpHeaders httpHeaders = new HttpHeaders();
    ResponseEntity<String> sendGet = http.sendGet(someUrl1, httpHeaders);
    ResponseEntity<String> sendPost = http.sendPost(someUrl2, httpHeaders);                 
                    
}catch(HttpClientErrorException e) {

   //print call url here someUrl1/someUrl2
   printException(e);
}
catch (Exception e) {
    printException(e);
    //general e             
}

//Print exception
public void printException(Exception e){
     //log URL here
}

我想在捕获异常时打印失败的 URL,但我没有找到可以使用的 HttpClientErrorExceptionRestClientException 属性。

【问题讨论】:

    标签: java spring-boot rest http resttemplate


    【解决方案1】:

    一般情况下的编辑:

    我认为你不应该使用HttpClientErrorException 来获取 url,在调用每个请求之前你知道 URL,所以我的建议:

    创建一个接收 post 方法、URL 和 headers 参数的通用发送方法

    为每个请求调用您的方法,它还将根据当前 URL 处理异常

    对于有问题的简单案例描述

    您可以为每个请求拆分为 2 个尝试和捕获块

    或添加一个布尔值(或 currentUrl 字符串变量)

    boolean isFirstRequestFinished = false;
    

    在第一次请求后将其设置为 true 并签入 catch 块

    if (isFirstRequestFinished) { 
    

    【讨论】:

    • 我知道我可以做到,但如果可能的话,我想要一个通用的解决方案,假设我的 try 块中有 100 个调用。
    • @ItsikMauyhas 我会重构 send 方法来接收 post 方法、URL 和 headers,该方法还将处理基于当前 URL 的通用异常
    • 我知道我可以做到所有这些,我只想知道如何从异常对象中检索 URL,我们将异常对象发送到另一个打印它的方法,我不想更改该方法签名通过添加 URL 字符串。
    • @ItsikMauy 你的方法会调用内部泛型方法,所以方法签名没有变化
    • 这可行,但我仍然想了解如何从异常对象中获取 URL。
    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2018-09-24
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多