简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM