【发布时间】:2021-07-13 21:09:34
【问题描述】:
对于具有 try/catch 块的异步函数,我收到了 UnhandledPromiseRejectionWarning。我错过了什么?
// In local module http.js
async function get(url, callback) {
try {
const response = await axios.get(url)
if (callback) {
callback(null, response.data)
}
} catch (err) {
console.error("GET failed to "+url+" - "+err);
callback(err)
}
}
我这样调用函数。我没有在这里使用 await,因为我希望得到回调的结果:
http.get(config.hostController+"/v0/portal/subscribers/"+req.session.subscriberId, function(err, response){
if (err) {
return res.status(err).send(response)
}
return res.send(response)
})
我遇到了问题,因为我看到了“GET failed to”消息。 (我期待一个 404 错误)。但我仍然收到此错误:
GET failed to http://localhost:7991/v0/portal/subscribers/SUB-b4ae-2ed6 - Error: Request failed with status code 404
(node:23948) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: Error: Request failed with status code 404
at createError (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/core/createError.js:16:15)
at settle (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/Users/sjohnson/github/netreach/netreach-portal/node_modules/axios/lib/adapters/http.js:260:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
config: [Object],
request: [ClientRequest],
response: [Object],
isAxiosError: true,
toJSON: [Function: toJSON]
}
【问题讨论】:
标签: node.js async-await axios try-catch