In our application, it is crucial to differentiate between 400 and 500 range error codes for distinct processes.
Let's consider three REST calls:
- The first returns a status code of 200,
- the second returns 401,
- and the third returns 502
Initially, while using aurelia-http-client
, I encountered an unexpected http error with code = 0
in the promise reject callback.
Update: Switching to aurelia-fetch-client
resulted in receiving only a string as an error response, eliminating it as a viable option.
I then experimented with an ajax call
and a basic XMLHttpRequest
, but faced the same issue. The statusCode was always 0 for errors above the 200 range.
Update: To provide context, I am using Version 63.0.3239.132 of Chrome.
Attempts So Far:
I made about five different variations for fetch requests.
fetch(url, { method: requestMessage.method, headers, body: JSON.stringify(content) }) .then((result) => { resolve(result) }) .catch((error) => { reject(error); });
This resulted in a string error being displayed.
Using aurelia-http-client
:
this.httpClient.createRequest(url)
.asPut()
.withContent(params)
.send()
.then((response) => {
resolve(response);
},
(error) => {
reject(error);
});
- Errors consistently showed a StatusCode of 0
Additionally (Constructs a dynamic XmlHttpRequest):
private retryRequest(): void {
var xhr = this.setupXhr();
xhr.onreadystatechange = () => this.stateChange(xhr);
setTimeout(() => {
xhr.send(JSON.stringify(this.content));
}, 1000);
}
private setupXhr(): XMLHttpRequest {
var xhr = new XMLHttpRequest();
xhr.open(this.method, this.url, true);
xhr = this.addHeaders(xhr);
return xhr;
}
private addHeaders(xhr: XMLHttpRequest): XMLHttpRequest {
for (let key in this.headers) {
if (this.headers.hasOwnProperty(key)) {
xhr.setRequestHeader(this.headers[key].key, this.headers[key].value);
}
}
return xhr;
}
private stateChange(xhr: XMLHttpRequest): void {
logger.debug(' ::>> xhr = ', xhr);
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
this.resolve(JSON.parse(xhr.response));
} else if (xhr.status >= 500) {
this.retryRequest();
} else {
// this.retryRequest();
this.reject(xhr.response); // call after a # of fails for this ???
}
}
}
- This function exclusively captures the 200 range HTTP status codes
Moreover:
$.ajax({
type: requestMessage.method,
url,
data: JSON.stringify(content),
headers,
success: (data) => {
logger.debug(' ::>> rest call was a success ', data);
resolve(data);
},
statusCode: {
502: (jqXHR) => {
logger.debug(' ::>> received 502 ');
var retryAfter = jqXHR.getResponseHeader('Retry-After');
retryAfter = parseInt(retryAfter, 10);
if (!retryAfter) { retryAfter = 5 };
setTimeout(query, retryAfter * 1000);
}
}
});
- Despite specifying a 502 callback, it never triggers. I have attempted handling other status codes as well.
Could there be a solution to properly retrieve the error codes that I may have overlooked? Any assistance would be greatly appreciated.