4

I'm doing a simple UDP "send" using Node's inbuilt datagram UDP socket :

http://nodejs.org/docs/v0.3.1/api/dgram.html

The destination of the message is a domain name that has to be resolved by DNS before transmission.. node.js handles this.

In the event that DNS resolution fails dgram throws a "ENOTFOUND Domain Not Found" error and passes it to the callback that I've registered.

My code is like this:

client = dgram.createSocket("udp4");
client.send(message, 
            0, 
                message.length, 
                this.port, 
                this.address, 
                function(err, bytes) { 
                    if (err) { 
                        //get rid of error??
                        } 
                    }
                );
client.close();

I'm not particularly interested in the error.. if it fails, it fails, its not important to the business rules of the application. I'll log it to console for completeness.. BUT I cant stop this exception walking back up the stack and bringing down the application. How do I handle this error?

I dont wish to put a global uhandled exception handler in place just for this. I've tried rethrowing the error inside the callback within a Try/Except handler.. that didn't work.

Any thoughts?

Thanks for reading.

Duncan_m
  • 2,526
  • 2
  • 21
  • 19
  • Did you try with a try/catch and NOT rethrowing the error? Catching and containing the error should stop it from propagating back up the stack, unless something unfortunate happens behind the scenes before the error gets to you. – shelman Jun 25 '11 at 05:51
  • Hi Shelman, I hadnt tried that.. but I just did.. an empty try/catch block in the callback doesnt prevent the exception travelling back up the stack.. thanks though. – Duncan_m Jun 25 '11 at 05:58
  • This seems related.. looks like I might be stuck using a global unhandled exception handler. http://stackoverflow.com/questions/4328540/how-to-catch-http-client-request-exceptions-in-node-js – Duncan_m Jun 25 '11 at 12:51

1 Answers1

5

You need to listen for an error event from the socket. If you don't, then node will convert this to an exception. Do not try to handle this with uncaughtException, because the only safe thing to do from uncaughtException is log then exit.

Here is an example of listening for error and causing an intentional DNS error:

var dgram = require('dgram');
var message = new Buffer("Some bytes");
var client = dgram.createSocket("udp4");
client.on("error", function (err) {
    console.log("Socket error: " + err);
});
client.send(message, 0, message.length, 41234, "1.2.3.4.5");

This should print:

Socket error: Error: ENOTFOUND, Domain name not found

And the program will continue running.

Matt Ranney
  • 1,638
  • 12
  • 12