Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Express onError handler only handle "listen" errors?

The Express generator defines an onError() event handler that has this:

if (error.syscall !== 'listen') throw error;

The syscall is described as "a string describing the syscall that failed", of which there are many possible types of failures (on linux, not sure what would happen on windows).

So why is only a "listen" error handled - surely the node app can fail for other reasons? This is part of the express generator template, I'm sure there's a good reason for it.

like image 353
lonix Avatar asked Apr 09 '26 21:04

lonix


1 Answers

To answer this question, we have to look at the rest of the function:

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

Only errors of type 'EACCES' or 'EADDRINUSE' get special handling. Every other type of error is just thrown. Those error types will only ever coincide with error.syscall === 'listen'. So, if that condition isn't true, might as well throw it and exit early. It's a form of guard clause which aids readability.

like image 168
Big McLargeHuge Avatar answered Apr 12 '26 10:04

Big McLargeHuge