繁体   English   中英

是否应该在节点中监听 http.ClientReuqest 的“错误”事件?

[英]Should one listen to the "error" event of http.ClientReuqest, in node?

让我们以这段代码为例:

const https = require('https')
const options = {
    hostname: 'somesite.com',
    port: 443,
    path: '/',
    method: 'GET'
}

const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`)

    res.on('data', d => {
        //do something with each chunk..
    })
})

req.on('error', error => {//When will this event be fired, if ever?
    console.error(error)
})

req.end()

在许多示例中,我看到人们在收听此事件,但在查看文档时,我没有看到任何提及: https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_clientrequest

列出了各种“错误”事件,如“超时”、“中止”等,但没有“错误”。

也就是说,ClientRequest 是 tream.Writable 的一个实例(如果我是正确的),它确实会发出一个“错误”事件: https://nodejs.org/dist/latest-v14.x/docs/api/stream。 html#stream_event_error

我正在处理我真实代码中的超时和中止。 是否需要此错误侦听器?

该文档针对http.request()指定了这一点:

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object. 与所有“错误”事件一样,如果没有注册监听器,则会抛出错误。

因此,如果您不听error事件(无论是出于日志记录还是恢复目的),您的应用程序只会在任何此类错误情况下崩溃。

暂无
暂无

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

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