我可以在调用 http.get(url, cb)
时创建 4 个错误场景:
httpThrows()
可以通过错误的url格式或错误的回调等来触发
function httpThrows() {
try {
http.get("www.missing-protocol.com", res => {
console.log(res.statusCode);
});
} catch (error) {
console.log("http.get() throws an error.");
}
}
请求错误()
它是主要的错误处理程序并在某些网络相关问题上触发,例如DNS查询失败或服务器无响应等
function requestError() {
var req = http.get("http://some-url-that-does-not-exist.com", res => {
console.log(res.statusCode);
});
req.on("error", err => {
console.log("req.on('error') called with error");
});
}
错误码()
服务器正常响应所以没有网络错误(可以处理服务器错误)。
function errorCode() {
http.get("http://httpstat.us/501", res => {
console.log("Got error code:", res.statusCode);
});
}
responseError()(问题)
http.IncomingMessage
在回调中作为 response
或 res
给出。根据documentation它是一个 Readable steam
并且该 steam 可以发出一个 error
事件。
function responseError() {
http.get("http://some-ulr-with-error-halfway-through.com/", res => {
console.log(res.statusCode);
// This will never be emitted?
res.on("error", err => {
console.log("res.on('error') called with error", err);
});
});
}
所以最后一个处理程序:
- 使用
http.request
或http.get
时是否会触发此事件? - 如果可以,什么可以触发该事件?
最佳答案
据我所知,在这种情况下以错误结束的唯一方法是 Node 或引擎是否存在问题,而在这两种情况下您都无能为力。
在这种情况下,我宁愿不处理这些情况,因为您需要审查和维护的代码较少。
关于javascript - 'error' 事件是否会在 node.js http.request 中的 'http.IncomingMessage' 上发出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53691119/