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

后端 未结 2 948
南方客
南方客 2021-02-13 20:35

Currently converting my project to use Typescript. My previously working code to launch Express in Node looks like this:

server.listen(port, (error) => {
  if         


        
2条回答
  •  清酒与你
    2021-02-13 21:14

    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.

提交回复
热议问题