How to handle errors with Express .listen() (in Typescript)?

There is no error¹.

 server.listen(port, () => {
   console.info(`Ready on port ${port}`);
 });

To listen for errors, use server.listen(port).on("error", /*...*/) ².

¹: The docs are quite nested:

The Express docs say, that

This method is identical to Node’s http.Server.listen().

Now these docs say, that htt.Server.listen equals Net.server.listen.

And that then says:

This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callback will be added as a listener for the 'listening' event.

Now the "listening" event does not seem to raise any error.

²: Thats the recommended way I found in the Express issuetracker.

Note that in most cases you don't want to handle the error, if the server crashes, it is very likely that the best option is to just restart the whole process.


I ran into this today, too. Here's the (breaking) change to the type definition:

https://github.com/DefinitelyTyped/DefinitelyTyped/pull/47063

That PR's author suggests that the proper way to handle listen errors is by registering a listener (as linked by Jonas above):

https://nodejs.org/api/net.html#net_server_listen

It sounds like the type definitions were a lie, and that parameter didn't really exist, so removing its use from your app should be a no-op. That's what I'm doing. (furthermore, I'm okay with errors like EADDRINUSE crashing my app, so I'm not adding any new error handling)