我正在向后端发出 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/