CDenby
CDenby

Reputation: 95

How do I log 500 server errors with XMLHttpRequest in pure Javascript?

I generally have been using XMLHttpRequest to perform Ajax calls. However, when the server has an error, I'd like to console.log the error so that I don't have to run to the server to see the event log there.

Here's what I generally do:

function LoadPage(){
    var parameters="this=that";
    var x = new GetXmlHttpObject();
    x.open("POST", "Ajax.aspx?Function=LoadPage")
    x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    x.ontimeout = function () { location.reload(true); }
    x.send(parameters);
    x.onreadystatechange = function () {
        if (x.readyState === 4 && x.status === 200){
            //Do Stuff with the response
        }
    }

But if the server has an error with the request, I get the error on the x.send(parameters) line. I've tried to wrap that in a try..catch, but the error comes up in the console even with the command held inside the try.

How can I console.log the 500 errors from the server using this structure?

Upvotes: 2

Views: 4432

Answers (2)

rockawayz
rockawayz

Reputation: 1

Updated function

function LoadPage() {
      return new Promise(function(succeed, fail) {
        var req = new XMLHttpRequest();
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.open("POST", "Ajax.aspx?Function=LoadPage", true);
        req.ontimeout = function () { location.reload(true); }
        req.addEventListener("load", function() {
          if (req.status < 400)
            succeed(req.responseText);
          else if (req.status == 500)
            fail("Error 500: Internal Server Error");
          else
            fail(new Error("Request failed: " + req.statusText));
        });
        req.addEventListener("error", function() {
          fail(new Error("Network error"));
        });
        req.send("this=that");
      });
    }

Usage:

LoadPage().then(function(text) {
  console.log("data.txt: " + text);
}, function(error) {
  console.log("Failed to fetch data.txt: " + error);
});

Upvotes: -1

Quentin
Quentin

Reputation: 943097

But if the server has an error with the request, I get the error on the x.send(parameters) line.

That won't happen. The client can't react to the response in any way before the response has arrived.


I've tried to wrap that in a try..catch

That won't work for two reasons.

  • It is asynchronous
  • It doesn't throw an exception

if (x.readyState == 4 && x.status == 200){

You're already testing for a 200 status here. Test for a 500 status in the same way.

Upvotes: 4

Related Questions