[英]Axios error status code UnhandledPromiseRejectionWarning
Using axios, I'm making GET requests to multiple links to test to see if they are broken links.使用 axios,我向多个链接发出 GET 请求以测试它们是否是断开的链接。 If the GET requests returns an error, I want to log this error to the console and send it to the client side with socket.
如果 GET 请求返回错误,我想将此错误记录到控制台并通过套接字将其发送到客户端。 However, on some links (not all), I get an
UnhandledPromiseRejectionWarning
.但是,在某些链接(不是全部)上,我收到了
UnhandledPromiseRejectionWarning
。
// check if the link is dead
axios.get(linkHref, {
auth: {
username: USERNAME,
password: PASSWORD
}
})
.then( (response) => {
if (response.status != 200) {
resultData = {
text: linkText,
url: linkHref,
statusCode: String(response.status)
}
console.log(resultData);
io.sockets.emit("result", resultData); // send link to client-side
}
})
.catch( (error) => {
if (error) {
resultData = {
text: linkText,
url: linkHref,
statusCode: String(error.response.status) // this is where the error is
}
console.log(resultData);
io.sockets.emit("result", resultData); // send link to client-side
}
});
I expect it work correctly and return the status code of the error but sometimes I get a UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'status' of undefined
error.我希望它可以正常工作并返回错误的状态代码,但有时我会收到
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'status' of undefined
error。 But with my if statement in the .catch
, I am checking to make sure that there is an error and that it is not undefined so I don't understand why I'm getting this error.但随着我的if语句
.catch
,我检查,以确保有一个错误,它没有不确定,所以我不明白为什么我得到这个错误。
EDIT: Also, this works (does not show me that error) when I run it on my Mac but not in Windows ... why?编辑:另外,当我在 Mac 上运行它而不是在 Windows 中运行它时,这有效(没有向我显示该错误)......为什么?
hey can you check by validating whether you are getting the response property on the error object in the if else condition嘿,您可以通过验证是否在 if else 条件中获取错误对象的响应属性来检查
.catch( (error) => {
if (error.response) {
//rest of the code...
}
});
TypeError: Cannot read property 'status' of undefined
The response property on error.response is not defined eg error = { response: undefined }
. TypeError: Cannot read property 'status' of undefined
的TypeError: Cannot read property 'status' of undefined
error.response 的响应属性,例如error = { response: undefined }
。 Therefore, referencing any properties on it throws an error.因此,引用其上的任何属性都会引发错误。
error.response[property]
Also on failed/hanging http requests the error argument is different.同样在失败/挂起的 http 请求上,错误参数也不同。 Checkout this gistaxios-catch-error .
查看这个要点axios-catch-error 。 The error argument will have different properties for this case.
在这种情况下,错误参数将具有不同的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.