Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I seeing DBI errors on the console even though I have wrapped the DBI calls in an eval?

Tags:

perl

eval

dbi

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
}
like image 226
Ben Dauphinee Avatar asked Nov 30 '22 18:11

Ben Dauphinee


1 Answers

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.

like image 105
Ether Avatar answered Dec 05 '22 14:12

Ether