how to access original request from onComplete function while processing httpClient response

I am making a few HTTP POSTs to the back-end using JavaScript (httpClient.send) Following anti-pattern guidelines, onComplete() function is used to process the responses.

Things work well until there is an error. For the error response I need to understand what the request was. For instance, second request out of three failed.

Is it possible to access the original request in onComplete function or correlate it somehow?

Solved Solved
1 2 453
1 ACCEPTED SOLUTION

yes, but you need to preserve the request in some way, perhaps with a closure. Like this:


function generateOnComplete(req) {
  return function onComplete(response, error) {
    if ( ! response) {
      throw new Error('request failed');
    }
    if (response.status == 200) {


    }
    else {
      // the variable 'req' here holds the original request
      ...
    }
  };
}


var payload = JSON.stringify({
      foo : 'bar',
      whatever : 1234
    });
var headers = {
      'Content-Type' : 'application/json',
      'Authorization' : 'Bearer xyz'
    };
var url = 'https://example.com/path2';
var req = new Request(url, 'POST', headers, payload);


httpClient.send(req, generateOnComplete(req));


View solution in original post

2 REPLIES 2

yes, but you need to preserve the request in some way, perhaps with a closure. Like this:


function generateOnComplete(req) {
  return function onComplete(response, error) {
    if ( ! response) {
      throw new Error('request failed');
    }
    if (response.status == 200) {


    }
    else {
      // the variable 'req' here holds the original request
      ...
    }
  };
}


var payload = JSON.stringify({
      foo : 'bar',
      whatever : 1234
    });
var headers = {
      'Content-Type' : 'application/json',
      'Authorization' : 'Bearer xyz'
    };
var url = 'https://example.com/path2';
var req = new Request(url, 'POST', headers, payload);


httpClient.send(req, generateOnComplete(req));


Oh. My mind had been sleeping 😞

Thank you a lot for the response.