0

I have trouble caughting error during create object in Perl. My part of current code is like that:

#!/usr/bin/perl
use Mail::SpamAssassin::Client;
use warnings;
use strict;

my $client = new Mail::SpamAssassin::Client({port => 783, host => 'localhost'});
my $message = '';

if(!$result) {
    print "Cant process a message ! Error: " . $result;
}

So I cant check $client variable if object has been created properly. Only I can check only $result variable after calling the method $client->process($message) But this is not satisfactory for me. Example if spammassassin daemon will be offline then I got communicate in terminal:

Failed to create connection to spamd daemon: Connection refused

Maybe can I catch this error message or error code after calling static method ?

Macsurf
  • 17
  • 6

1 Answers1

2

The module does this:

unless ($remote) {
  print "Failed to create connection to spamd daemon: $!\n";
  return;
}

ug. A module shouldn't do this. Worse, it writes to STDOUT instead of STDERR!

...Actually, it writes to the default file handle, which is normally STDOUT, but this can be changed using select. This presents a solution to us.

use Scope::Guard qw( guard );

sub validate {
   my ($client) = @_;
   open(my $fh, ">", $^O eq 'Win32' ? 'nul' : '/dev/null')
      or die $!;

   my $old_fh = select($fh);
   my $guard = guard { select($old_fh); };
   return $client->ping();
}

my $rv = eval { validate($client) };
die($@) if $@;
die($!) if !$rv;

That performs a ping request and returns and checks for the response. If you want to check creating the connection and nothing else, you can use

use Scope::Guard qw( guard );

sub validate {
   my ($client) = @_;
   open(my $fh, ">", $^O eq 'Win32' ? 'nul' : '/dev/null')
      or die $!;

   my $old_fh = select($fh);
   my $guard = guard { select($old_fh); };
   return !!$client->_create_connection();
}

validate($client)
   or die($!);

Note that the module creates a new connection for every method call, so it's possible a check could pass, but a later call could fail (e.g. because of a network issue).

ikegami
  • 367,544
  • 15
  • 269
  • 518