Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!