How to check error in express listen callback?

Viewed 2726

I have the following code to check whether there was an error starting Express:

express()
    .listen(port, (err: Error) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log(`Express started`);
    });

However, recently, I'm getting this error in Typescript compiler:

TS2345: Argument of type '(err: Error) => void' is not assignable to parameter of type '(() => void) | undefined'.

It seems like the callback function of listen() doesn't take in an error parameter. If this is the case, how should I check and handle errors when starting Express?

1 Answers

The Server object is a Node.js EventEmitter. As with all EventEmitters, most errors are passed to the 'error' event. So you can catch like this:

express().listen(port, () => {
   console.log('Listening on port: ', port);
}).on('error', (e) => {
   console.log('Error happened: ', e.message)
});

I hope this will be useful.

Related