• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

245
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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error