Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node js throw exception in events

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading