简体   繁体   English

从Express Server提取时的错误对象

[英]Error Object When Fetching From Express Server

I have an Express server with a simple error handler. 我有一个带有简单错误处理程序的Express服务器。 All the err object passed to it are Error objects. 传递给它的所有err对象都是Error对象。

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调用服务器的路由:

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. 我的问题是错误不是作为error对象通过,而是作为body对象上的error属性通过。

How should I have Express set up so that I get error objects back? 我应该如何设置Express以使错误对象返回?

A 500 status is NOT reported by request.post() as an error. request.post()将500状态报告为错误。 The http server was contacted and a response was supplied. 已与http服务器联系,并提供了响应。 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. 由您自己的代码决定是否从http响应中检测到该条件,然后将其视为您自己的代码中的错误。

You will need to look at the actual response to see the http 500 status code. 您将需要查看实际响应以查看http 500状态代码。 The error object IS the http response body so that's where it should be. 错误对象是http响应正文,因此应该在此处。 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. 如果必须在多个地方执行相同的逻辑,则可以为request.post()创建自己的包装函数,该函数将检查http状态代码,并且如果该范围处于您认为错误的范围内,则获取http响应正文并把它变成一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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