Maximus Maximus - 1 month ago 7
Node.js Question

How to listen for error happening inside `request.on('end',`

I have this code which throws an error from

concat
method:

request.on('end', function (chunk) {
body = Buffer.concat(body).toString();
});


I wanted to be notified about the error so I added a listner:

request.on('error', function (error) {
var e = error;
})


But it's not triggered. Why? How can I listen to it using
error
event without using
try/catch
?

This is not a question about why I get the error, this is the question how to catch it using
error
event

Answer

It does not trigger because the event that fire error is internal to the request object and your problem is in another scope.

You could use a try/catch instead when calling Buffer.concat

request.on('end', function (chunk) {
    try {
      body = Buffer.concat(body).toString();
    } catch (e) {
      // do something with "e"
    }
});