Home > Net >  How to handle errors while setting the name server with Net::DNS
How to handle errors while setting the name server with Net::DNS

Time:08-09

I am setting the name server used by the resolver with Net::DNS

my $resolver = Net::DNS::Resolver->new();
$resolver->nameservers( $somenameserver );

If the argument is wrong, an error is printed on standard error. E.g.,

unresolvable name: uuu.aaa.eee at check_rbl line 145.

and the functions returns 0, if everything is OK then 1 is returned.

So far, so good.

I would like to suppress the error message on standard error and perform a custom action.

How can I avoid the automatic error message? And how I get the error message?

CodePudding user response:

You can use Capture::Tiny for this.

Btw ->nameservers() returns all valid nameservers in a list context. If all nameservers passed are invalid, it returns an empty list.

If you change @servers to a scalar value $server you get an undef.

use Net::DNS::Resolver;
use Capture::Tiny qw(capture);

my $res = Net::DNS::Resolver->new();

my ($stdout, $stderr, @servers) = capture {
    $res->nameservers("8.8.8.8a");
};

if ( @servers == 0 ) {
    printf "Error found: %s\n", $stderr;
}
else {
    print "Everything fine.\n";
}
  • Related