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

Node.js Request why is 400 response being caught in try catch

我正在向后端发出 HTTP 请求。请求 returns 一个 400 的正文告诉我为什么这是一个错误的请求。

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

如果我直接在邮递员中尝试后端请求,我可以看到带有 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
}