title: How to handle a POST request error using XMLHttpRequest() and Javascript
body: <p>I am trying to handle an error thrown by a HTTP request, but am unable to properly intercept the event.</p>
  
  <blockquote>
    <p>POST <a href="http://localhost:8080/path/to/endpoint" rel="nofollow noreferrer">http://localhost:8080/path/to/endpoint</a> 500 (Internal Server Error)</p>
  </blockquote>
  
  <p>I have a drop zone on the page that receives a file and parses it on a server. When the file is properly formatted it works well, but am trying to handle errors caused by improperly formatted documents.</p>
  
  <p>According to the Mozilla docs the XMLHttpRequest has an onerror function, but it's getting bypassed when I try to use it as follows:</p>
  
  <pre><code>_postRequest() {
    let files = this.files[0];
    let data = new FormData();
    let request = new XMLHttpRequest();
  
    // File selected by the user - in case of multiple files append each of them
    data.append('file', this.files[0]);
  
    // AJAX request finished
    request.addEventListener('load', (e) =&gt; {
      // Send response to DOM
      this.dispatchEvent(new CustomEvent('return-validated-items', {
        bubbles: true, composed: true,
        detail: request.response
      }));
    });
  
    // If server is sending a JSON response then set JSON response type
    request.responseType = 'json';
  
    // Send POST request to the server side script
    request.open('post', 'http://localhost:8080/path/to/endpoint');
    request.onerror = function () { // This function is not working properly
      console.log("** An error occurred during the transaction");
    };
    request.send(data);
  }
  </code></pre>
  
  <p>I was also having issues with this alternative method:</p>
  
  <pre><code>try {
    request.open('post', 'http://localhost:8080/path/to/endpoint');
    request.send(data);
  } catch (e) {
    console.log(e)
  }
  </code></pre>
  
  <p>How can I handle an error caused by <code>request.send()</code>?</p>