最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check error in express listen callback? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jun 5, 2019 at 17:45 CarvenCarven 15.7k30 gold badges124 silver badges183 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 23

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.

发布评论

评论列表(0)

  1. 暂无评论