如何在node.js中捕获zlib错误
我从一个可能被压缩的服务器下载内容,所以我使用了我在不同地方找到的这个样板:如何在node.js中捕获zlib错误,node.js,exception-handling,zlib,Node.js,Exception Handling,Zlib,我从一个可能被压缩的服务器下载内容,所以我使用了我在不同地方找到的这个样板: var file = fs.createWriteStream(filename); var request = https.get(url, function(response) { switch (response.headers['content-encoding']) { case 'gzip': response.pipe(zlib.cr
var file = fs.createWriteStream(filename);
var request = https.get(url, function(response) {
switch (response.headers['content-encoding']) {
case 'gzip':
response.pipe(zlib.createGunzip()).pipe(file);
break;
case 'deflate':
response.pipe(zlib.createInflate()).pipe(file);
break;
default:
response.pipe(file);
break;
}
file.on('finish', function() {
console.log("Done: "+url);
file.close(function() {});
});
}).on('error', function(err) { // Handle errors
fs.unlink(filename, function() {});
console.log(err+" "+url);
});
问题是,如果HTTPS请求因网络错误而失败,我有时会引发以下异常:
Error: unexpected end of file
at Zlib._handle.onerror (zlib.js:363:17)
该“错误”事件处理程序未捕获异常。那么如何捕获它,以便正确清理文件并知道如何重试?您有与请求相关的错误处理程序,但没有与解压缩和保存文件相关的错误处理程序。 尝试捕获解压缩流中的错误:
var decompressed;
switch (response.headers['content-encoding']) {
case 'gzip':
decompressed = response.pipe(zlib.createGunzip());
break;
case 'deflate':
decompressed = response.pipe(zlib.createInflate());
break;
default:
decompressed = response;
break;
}
decompressed.on('error', function(err) {
// handle error
});
decompressed.pipe(file);
如需更多阅读,请遵循以下答案-这些是异步函数。他们马上回来。例外情况会在稍后发生。没有什么值得一试的。太好了!我试试看。不幸的是,它很难复制。我会回来给你电话的√ 如果我不再看到异常情况。:)我通过删除它下载的文件的写访问权限来模拟它,因此会出现低级IO错误,这捕获了它,所以我接受了答案。非常感谢你@JoshuaSmith我编辑了答案,因为我捕获了与编写文件相关的错误,但忽略了与解压缩相关的错误。现在答案是正确的。