Search code examples
javaspring-bootresthttpresttemplate

Spring HttpClientErrorException and RestClientException getting request URL


I have more then 1 http call in try-catch block, exmaple:

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
}

I want to print the failed URL when I catch the exception but I did not find HttpClientErrorException or RestClientException property that I can use.


Solution

  • EDIT for general case:

    I don't think you should use HttpClientErrorException for getting url, you know the URL before calling each request, so my suggestion:

    Create a generic send method which receive post method, URL and headers parameters

    Call your method for each request and it will also handle exceptions based on current URL

    For simple case describe in question:

    You can split to 2 try and catch blocks for each request

    Or add a boolean ( or currentUrl String variable)

    boolean isFirstRequestFinished = false;
    

    Set it to true after first request and check in catch block

    if (isFirstRequestFinished) {