Writing below code, I am expecting that error occurred during server starting or starting of listening will be catched in the catch block.
const HTTP = require("http");
try {
HTTP.
createServer((request, response) => {
console.log(request);
console.log(response);
}).
listen(3000, () => { console.log("started") });
} catch (error) {
console.error(error);
}
Actually, it did not happen. For example, if execute two instances of above file, the second one will crush with
Error: listen EADDRINUSE: address already in use :::3000
CodePudding user response:
You can use
process.on('uncaughtException', function(e){
console.log(e);
});
To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.
CodePudding user response:
You need to listen on the error
event to get the error message.
server.on('error', (err) => {
throw err;
});
More complete code
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
// NOTICE THIS CODE BLOCK
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
As you can see server.on('error')
is listening to the emitted error and throwing it back. You can wrap it in try catch block to get the error.
CodePudding user response:
An alternative to using server.on
and listening to the event yourself is to make a promise that waits for the listening
and error
events.
const HTTP = require("http");
const { once } = require("events");
(async function() {
try {
const server = HTTP.
createServer((request, response) => {
console.log(request);
console.log(response);
});
server.listen(3000, () => { console.log("started") });
await once(server, 'listening');
console.log('started (2)');
} catch (error) {
console.error(error);
}
})();
Note:
- You can only use
await
outside of a function ("top level await") in some cases, so this example is wrapped in(async function() {})()
once
will catch errors whilelistening
has not been emitted yet. As soon aslistening
is emitted, the code continues.- Read more about
events.once
here.