Node.js 请求为什么在 try catch 中捕获 400 响应

标签 node.js express request request-promise

我正在向后端发出 http 请求。该请求返回 400,其正文告诉我为什么这是一个错误的请求。

但是为什么它被捕获在try catch中,为什么没有被返回 指标变量。

如果我直接在 postman 中尝试后端请求,我可以看到带有 400 状态的正文响应,因此请求成功。我假设请求只有在不成功的情况下才会被捕获。

 public async processMetrics(sessionId: any, side: any): Promise<any> {

        try {

                metrics = await this.getMetrics(session._id, sessionRequest._id);
                // Metrics not returned here               
        } catch (err) {
            console.log("CAUGHT 400");


        }

    }

--

public async getMetrics(sessionId: any, requestId: any): Promise<any> {

    const url = this.config.backendUrl + "/check/metrics";

    const options = {
        uri: url,
        headers: {
            "X-IDCHECK-SESSION_ID": sessionId,
        },
        body: {},
        json: true,
        resolveWithFullResponse: true,
    };

    return request.get(options);

}

我正在使用请求包 - https://github.com/request/request https://github.com/request/request-promise-native

最佳答案

如果状态代码为非 2xx,

request-promise 将拒绝。为了避免这种情况,您必须传递 simple: false 作为选项。

您可以在 documentation 中查看这一点

var options = {
    uri: 'http://www.google.com/this-page-does-not-exist.html',
    simple: false    //  <---  <---  <---  <---
};

rp(options)
    .then(function (body) {
        // Request succeeded but might as well be a 404
        // Usually combined with resolveWithFullResponse = true to check response.statusCode
    })
    .catch(function (err) {
        // Request failed due to technical reasons...
    });

If the request fails completelty with no response i still want that to be caught in the try catch

public async getMetrics(sessionId: any, requestId: any): Promise<any> {

    const url = this.config.backendUrl + "/check/metrics";

    const options = {
        uri: url,
        headers: {
            "X-IDCHECK-SESSION_ID": sessionId,
        },
        body: {},
        json: true,
        simple: false,
        resolveWithFullResponse: true,
    };

    const response = await request.get(options);

    if(!response.body)
       throw new Error('Empty body');

    return response
}

关于Node.js 请求为什么在 try catch 中捕获 400 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165552/

相关文章:

javascript - 使用 Mongoose 保存

mysql - 如何在sequelize、node js中使用like in where条件

mongodb - 无法获取/express.js 路由

javascript - 将对象数组传递给curl

node.js - 无法使用任何环境变量

node.js - npm 已安装,但运行 "sudo apt-get install npm"会出现错误。为什么?

node.js - Mongoose 查询中是否有相当于 Promise.all 的东西?

node.js - Mongoose 保存方法不起作用

python - 在自定义 Django 日志记录处理程序中检索请求对象

python-3.x - python : Access Denied at Random Points When Using Requests