Search code examples
javascriptnode.jshttp

Should one listen to the "error" event of http.ClientRequest, in node?


Let's take this code for example:

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()

In many examples i see people listening to this event, but when looking at the docs, i see no mentioning of it: https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_clientrequest

There are various "erroneous" events listed, like "timeout", "abort" and such, but no "error".

That said, ClientRequest is an instance of tream.Writable(if i'm correct), which does emit an "error" event: https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_event_error

I'm taking care of timeouts and aborts in my real code. Is there any need for this error listener?


Solution

  • The documentation specifies this with regards to 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. As with all 'error' events, if no listeners are registered the error will be thrown.

    So if you don't listen to the error event - be it for logging or recovery purposes -, your application will just crash in any such error scenarios.