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?
1 Answer
Reset to default 23The 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.