[英]How can I turn a Node.js http.IncomingMessage into a Fetch Request object?
[英]Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request?
调用http.get(url, cb)
时,我可以创建4种错误情况:
可以使用错误的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);
});
}
在回调中提供http.IncomingMessage
作为response
或res
。 根据文档,它是Readable 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或Engine出现问题,并且在这两种情况下您都无法做很多事情。
在这种情况下,我不想处理这些情况,因为您需要检查和维护的代码较少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.