Home > Software design >  Try/catch does not catch the error of 'listen' method of 'http', the NodeJS modu
Try/catch does not catch the error of 'listen' method of 'http', the NodeJS modu

Time:02-22

Writing below code, I am expecting that error occurred during server starting or starting of listening will be catched in the catch block.

const HTTP = require("http");

try {

  HTTP.
    createServer((request, response) => {
      console.log(request);
      console.log(response);
    }).
    listen(3000, () => { console.log("started") });

} catch (error) {

  console.error(error);

}

Actually, it did not happen. For example, if execute two instances of above file, the second one will crush with

Error: listen EADDRINUSE: address already in use :::3000

CodePudding user response:

You can use

process.on('uncaughtException', function(e){
    console.log(e);
});

To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.

CodePudding user response:

You need to listen on the error event to get the error message.

server.on('error', (err) => {
  throw err;
});

More complete code

const net = require('net');
const server = net.createServer((c) => {
  // 'connection' listener.
  console.log('client connected');
  c.on('end', () => {
    console.log('client disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});


// NOTICE THIS CODE BLOCK
server.on('error', (err) => {
  throw err;
});

server.listen(8124, () => {
  console.log('server bound');
});

As you can see server.on('error') is listening to the emitted error and throwing it back. You can wrap it in try catch block to get the error.

CodePudding user response:

An alternative to using server.on and listening to the event yourself is to make a promise that waits for the listening and error events.

const HTTP = require("http");
const { once } = require("events");

(async function() {
  try {

    const server = HTTP.
      createServer((request, response) => {
        console.log(request);
        console.log(response);
      });
    server.listen(3000, () => { console.log("started") });
    await once(server, 'listening');
    console.log('started (2)');

  } catch (error) {

    console.error(error);

  }
})();

Note:

  1. You can only use await outside of a function ("top level await") in some cases, so this example is wrapped in (async function() {})()
  2. once will catch errors while listening has not been emitted yet. As soon as listening is emitted, the code continues.
  3. Read more about events.once here.
  • Related