ivbtar
ivbtar

Reputation: 879

Error handling in perl

I have run.pl and decrypt.pm

run.pl :

my $secret2 = "test password";
my $ret=decrypt::decodeIt($secret2);
print $ret;

decrypt.pm :

sub decodeIt {
$tmp="";
.........
.........
.........
return $tmp
}

I am calling decodeIt() sub in run.pl. But something goes wrong in decodeIt sub and run.pl throws errors. I dont want to see these error exception to be printed it the screen and i want to catch the error in run.pl and do something else if there is an error like below. I tried like below but couldnt catch error.

if(!decrypt::decodeIt($secret2)){
print "Error in decode";
} else {
my $ret=decrypt::decodeIt($secret2);
print "No Error :".$ret;
}

Now the errors i see in screen are;

Argument "te" isn't numeric in int at decrypt.pm line 61.
Illegal hexadecimal digit 's' ignored at decrypt.pm line 64.
Illegal hexadecimal digit ' ' ignored at decrypt.pm line 64.
Illegal hexadecimal digit 's' ignored at decrypt.pm line 64.
Illegal hexadecimal digit 's' ignored at decrypt.pm line 64.
Illegal hexadecimal digit 'o' ignored at decrypt.pm line 64.
substr outside of string at decrypt.pm line 68.
Use of uninitialized value $string in length at decrypt.pm line 69.

I don't want to see these errors on screen. I just want to understand if there is an error and do some action if there is an error.

Upvotes: 1

Views: 356

Answers (1)

Borodin
Borodin

Reputation: 126762

You need to use the block version of eval to handle exceptions

However, most of the messages you are seeing are warnings, which aren't trapped by eval, and need to be escalated to fatal errors if you want to trap them

In this code, use warnings 'FATAL' will make every warning fatal for the duration of the current lexical context. The eval block will return undef if there is a fatal error, otherwise it will return the value of the decrypt::decodeIt call

I'm not very happy about masking the error message altogether. All you will be told is that there was a problem, without any indication of what it was. I think you should reconsider this

my $ret = eval {
    use warnings 'FATAL';
    decrypt::decodeIt($secret2);
};

if ( defined $ret ) {
    print "No Error: $ret\n";
}
else {
    print "Error in decode\n";
}

Upvotes: 1

Related Questions