Node js throw exception in events


I am wondering how to throw an error or returning value from event.

My code looks like this:

            const errorValidation = this.errorValidation
            const HOST = ""
            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) {
            this.socket.on('close', function(e) {
                console.log('Connection closed');
            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?


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.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published