Maximus Maximus - 1 year ago 85
Node.js Question

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

I have this code which throws an error from


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
event without using

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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download