I am wondering how to throw an error or returning value from event.
My code looks like this:
_initConnection(){
try{
const errorValidation = this.errorValidation
const HOST = "192.168.2.32"
const PORT = 8282
this.socket = net.createConnection(PORT, HOST)
this.socket.on('data', function(data) {
errorValidation(data)// throwing error
console.log('Received: ' data);
return data
});
this.socket.on('err', function(err) {
console.log('Connection' err);
});
this.socket.on('close', function(e) {
console.log('Connection closed');
});
}catch(err){
throw err
}
}
But because of the event throwing error is impossible it crash the app what should I do? Is using a Promies is a good guess?
CodePudding user response:
Your problem is, essentially, the same as How do I return the response from an asynchronous call?.
In your try/catch
block you assign a function which will run, in the future, whenever there is a data
event.
The try/catch
block then finishes (as does the function it is inside).
Later, in the future, you want to throw an exception, but you can't catch it in the try/catch
block you had because it doesn't exist any more. The security guard watching for trouble has packed up and gone home.
If you want to handle errors relating to the data
event, then you need to do it inside the function that runs when there is a data
event. It is the only thing available to do that at the right time.
CodePudding user response:
You can throw error like this in catch block.
throw new Error('some error message')
Refer docs for error handling in express