简体   繁体   English

表达-捕获请求失败错误

[英]express - catch request failed error

I am using the request module to send requests to a URL 我正在使用请求模块将请求发送到URL

var req = require('request');

when the response is received, I would like to write that file on the node server, so I am piping it to crateWriteStream 当收到响应时,我想在节点服务器上写入该文件,因此我将其传送到crateWriteStream

req.get(myUrl)
     .on('error', function(err) {
        console.log('there is an error');
     })
.pipe(fs.createWriteStream('userdir/abc.png'));

This works fine if there is no error returned by req.get. 如果req.get没有返回错误,则此方法工作正常。 In case req.get, fails I would like to not write the file locally and instead do something else. 万一req.get失败,我想不在本地写入文件,而是做其他事情。

I introduced .on('error'..) for this but the on('error') code never gets executed and .pipe tries to write the file that does not exist. 我为此介绍了.on('error'..),但是on('error')代码从未执行过,.pipe尝试写入不存在的文件。

How can catch an error returned by req.get() and only write when there is no error. 如何捕获req.get()返回的错误并仅在没有错误的情况下写入。

I think you are using streams but normally you can use the callback to receive the all information and then check if there is any error. 我认为您正在使用流,但是通常您可以使用回调来接收所有信息,然后检查是否有任何错误。

Personally I would do something like: 我个人会做类似的事情:

 var req = require('request'); req.get(myUrl, function (error, response, body) { if (error || response.statusCode != 200) { console.log(error) // Do something with your error } // If no errors, this code will be executed // Write in file }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM