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

后端 未结 2 949
南方客
南方客 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.

    0 讨论(0)
  • 2021-02-13 21:27

    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)

    0 讨论(0)
提交回复
热议问题