Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

You can throw error like this in catch block.

throw new Error('some error message')

Refer docs for error handling in express

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!