我正在向后端发出http请求。该请求返回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
答案 0 :(得分:1)
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...
});
如果请求失败,则完全没有 响应,我仍然希望被尝试捕获
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
}