Undistraction
Undistraction

Reputation: 43589

Error Object When Fetching From Express Server

I have an Express server with a simple error handler. All the err object passed to it are Error objects.

const errorHandler = (err, req, res, next) => {
  logError(`Express Error Handler: ${err}`);
  res.status(500).json(err);
};

I am calling the server's routes using request:

request
  .post(
    {
      uri: url,
      timeout,
      json: true,
      form: {
        currentStepUid,
        sourceStepUid: previousStepUid,
        config,
      },
    },
    (error, response, body) => {
      // Handle errors
    }
  )
});

My problem is that the error are not coming through as error objects, but rather as an error property on the body object.

How should I have Express set up so that I get error objects back?

Upvotes: 0

Views: 53

Answers (1)

jfriend00
jfriend00

Reputation: 707218

A 500 status is NOT reported by request.post() as an error. The http server was contacted and a response was supplied. That is not what it considers an error. It is up to your own code to detect that condition from the http response and then treat it as an error in your own code.

You will need to look at the actual response to see the http 500 status code. The error object IS the http response body so that's where it should be. That's where you need to get it from.

If you have to do this same logic in multiple places, you could make your own wrapper function for request.post() that would examine the http status code and if it's in a range that you consider an error, then get the http response body and make that into an error.

Upvotes: 2

Related Questions