I have a database query that I am running inside an eval, to trap the error. Problem is that the error message is outputting to console, even though it is being trapped. How do I stop the error message from doing this, as I want to parse it myself and spit back my own messages?
my $dbh = DBI->connect('dbi:Pg:dbname=database;host=localhost',
'user', 'pass',
{RaiseError => 1}
);
eval{
$sth = $dbh->prepare($sql);
$sth->execute;
};
if($@){
#Do my parse/print stuff here I know
}
It's not a good idea to trap and ignore errors, whether they are fatal or not. Also, it is not advisable to check $@ in the way you are doing it (see the questions on this site about perl exceptions for better ways to trap exceptions; I use Try::Tiny below, which is arguably the lightest-weight route of all).
Instead of proceeding with a DBI operation when an earlier one might have failed, you should check error conditions at every step:
use strict; use warnings;
use Try::Tiny;
try {
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute or die $sth->errstr;
} catch {
print "got error $_\n";
# return from function, or do something else to handle error
};
And remember, always use strict; use warnings;
in every module and script. Your code excerpt suggests that you are not yet doing this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With