如何使用Express .listen()处理错误(在Typescript中)? [英] How to handle errors with Express .listen() (in Typescript)?

查看:373
本文介绍了如何使用Express .listen()处理错误(在Typescript中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前将我的项目转换为使用Typescript.我以前在Node中启动Express的工作代码如下:

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

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

现在,我得到一个Typescript错误:

With this I now get a Typescript error:

Argument of type '(error: any) => void' is not assignable to parameter of type '() => void'.

我尝试将类型分配给诸如error: Errorerror: any之类的参数,但这不能解决问题.我在这里做什么错了?

I've tried assigning a type to the argument such as error: Error or error: any but this doesn't solve the problem. What am I doing wrong here?

而且,由于我是Typescript的新手,虽然我已经找到了很多学习Typescript的资源,但是在npm软件包更特定的情况下,我有什么地方应该寻找如何处理Typescript的? /p>

Also, since I'm new to Typescript, whilst I've found plenty of resources for learning Typescript generally, is there any where I should be looking to know how to deal with Typescript in scenarios more specific to npm packages?

推荐答案

没有error¹.

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

要侦听错误,请使用server.listen(port).on("error", /*...*/)².

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

¹:文档非常嵌套:

快速文档表示,

此方法与Node的http.Server.listen()相同.

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

现在这些文档说,htt.Server.listen等于Net.server.listen.

然后说:

此函数是异步的.当服务器开始监听时,将发出监听"事件.最后一个参数回调将添加为监听"事件的侦听器.

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.

²:这是我在 Express issuetracker 中找到的推荐方法.

²: 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.

这篇关于如何使用Express .listen()处理错误(在Typescript中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆