The usual way to catch exceptions is with an eval block or Try::Tiny etc.
Basic example:
my $source_address = eval { $res->query(....); };
if ($@) {
# an error occurred - $@ will contain the message
# do something appropriate here
}
However, $resolver->query() should, according to the docs, just return undef if no answers are found, and your example output suggests that execution gets to your "query failed:" warning in the else block, so
something else is happening after that - something which we have no idea, since we're not seeing the whole code.