rajesh verma
rajesh verma

Reputation: 11

How to handle multiple error code scenario in http request

Error codes below :-

400 - perform single retry on response arrival without delay

502, 503 and 504 perform eight number of retries with 1000 Sec delay

My code is below :-

private _getData('loginKey', body, headers) {
return this._http.post('url', body, { headers: headers })
  .map((response: Response) => response.json())
  .retryWhen(errors => {
    return errors
      .mergeMap((error) => this.handleError(error))
      .delay(2000)
      .take(8);
  });
}

public handleError(error: Response | any): Observable<any> {
  if (error.status === 400) { // retry 1 time and with no delay
    return Observable.of(error);
  } else { // retry confgured times and configured delay
    return Observable.of(error);
  }
}

My problem is how to change delay and take value according to the above Error codes:

if error.status is 400 then delay value 0 and take value 1

if error.status is 502, 503 and 504 then delay value 2000 and take value 8

Upvotes: 0

Views: 899

Answers (1)

Jeff Musser
Jeff Musser

Reputation: 121

The easiest way to do this is to define a function in a service that will return the value you want.

example:

let errorStatus;
private _getData('loginKey', body, headers) {
return this._http.post('url', body, { headers: headers })
  .map((response: Response) => response.json())
  .retryWhen(errors => {
    return errors
      .mergeMap((error) => {
          errorStatus = error.status;
          this.handleError(error))
      })
      .delay(ResponseService.getDelay(errorStatus))
      .take(ResponseService.getRetries(errorStatus));
  });
}

in ResponseService.js...

function getDelay(status) {
    let val = 0;
    switch(status) {
        case 400:
            val = 0;
            break;
        ...
    }
    return val;
}

function getRetries(status) {
    let val = 0;
    switch(status) {
        case 400:
            val = 1;
            break;
        ...
    }
    return val
}

Upvotes: 1

Related Questions