'fetch API - execute the same code after a connection timeout as if the response status code was not 200
I am trying to understand the fetch API a little better:
When making a GET-request such as below, I could simply check the status-code of the response and only then do something if the status-code equals 200.
let response = fetch(url, {method: 'GET'});
if (response.status === 200) {
// do something
} else {
console.log("GET request was not successfull");
}
I have read that it might be a good idea to set a connection timeout for the fetch-request. I could use an AbortController for this purpose:
function fetchWithTimeout(url, method) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 8000);
response = await fetch(url, {method, signal: controller.signal});
clearTimeout(timeoutId);
return response;
}
If the connection actually times out, an AbortError is thrown. In this case, I would like to log the exact same error message as if the connection did not time out, but the response status-code was not equal to 200. And I cannot think of any better solution for this than the following:
try {
let response = fetchWithTimeout(url, 'GET');
if (response.status === 200) {
// do something
} else {
console.log("GET request was not successfull");
}
} catch (AbortError e) {
console.log("GET request was not successfull");
}
I don't like this code, since it is redundant. In this case it is not too bad, as I am only logging a message. But potentially, I could do more and I just want to execute the same code for both scenarios. Does somebody have an idea as on how to achieve this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
