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

358
Views
Is it possible to make xhr.onerror fire implicitly?

I am building a helper for uploading files in react native, although I cannot get to fire xhr.onerror, I was hoping to throw an error inside onreadystatechange by checking for the status and the onerror would fire but unfortunately it isn't. Any good approach how I can handle this?

Here is the whole code:

sendXHR = async (
    url: string,
    formData: FormData,
    eventListeners: XMLHttpRequestEventTarget,
  ) => {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', `${API_URL}${url}`, true);
    const credentials: any = await retrieveToken();
    xhr.setRequestHeader('Authorization', `Bearer ${credentials.password}`);

    xhr.upload.onabort = eventListeners.onabort;
    xhr.upload.onprogress = eventListeners.onprogress;
    xhr.upload.onerror = eventListeners.onerror;
    xhr.upload.onloadstart = eventListeners.onloadstart;

    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
          const status = xhr.status;
          if (status < 200 || status >= 300) {
            throw new Error(xhr.statusText);
          }
      }
    };
    xhr.send(formData);

    return {
      response: new Promise((resolve, reject) => {
        xhr.onload = () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.response);
          } else {
            reject({status: xhr.status, message: xhr.statusText});
          }
        };
        xhr.onerror = () => {
          reject({status: xhr.status, message: xhr.statusText});
        };
      }),
      xhr,
    };
  };
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!