Re: DBD::pg error trapping?

From: David Wheeler <david(at)kineticode(dot)com>
To: Aditya <aditya(at)grot(dot)org>
Cc: sfpug(at)postgresql(dot)org
Subject: Re: DBD::pg error trapping?
Date: 2003-02-26 21:58:55
Message-ID: 8016172A-49D5-11D7-AC26-0003931A964A@kineticode.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: sfpug

On Wednesday, February 26, 2003, at 11:58 AM, Aditya wrote:

> my($dbh) = DBI->connect($data_source, $user, $dbpassword,
> {RaiseError => 0} #depends on whether you check errstr
> ) || die "couldn't call $data_source: $DBI::errstr\n";
> $dbh->{ChopBlanks} = 1;
> $dbh->{AutoCommit} = 1;
> $dbh->{RaiseError} = 0;
> $dbh->{PrintError} = 0;
>
> my $query = <<SQL;
> select foo from bar
> SQL
>
> my($sth) = $dbh->prepare($query);
> if ($dbh->err()){
> notify('crit', "ERROR: ($query) " . $dbh->errstr);
> }
> my($rv) = $sth->execute();
> if ($sth->err()){
> notify('crit', "ERROR: ($query) " . $sth->errstr);
> }

Ick. I much prefer to use exceptions:

use strict;
use DBI;

my $dbh = DBI->connect($data_source, $user, $dbpassword,
{ RaiseError => 1,
PrintError => 0,
ChopBlanks => 1,
AutoCommit => 1,
ShowErrorStatement => 1,
});

eval {
my $sth = $dbh->prepare("select foo from bar");
$sth->execute;
};

if (my $err = $@) {
# Do something with the exception.
print STDERR "Error: $(at)\n";
}

Even better is to use real exceptions, like my Exception::Class::DBI
module
from CPAN:

use strict;
use DBI;
use Exception::Class::DBI;

my $dbh = DBI->connect($data_source, $user, $dbpassword,
{ RaiseError => 1,
PrintError => 0,
ChopBlanks => 1,
AutoCommit => 1,
HandleError =>
Exception::Class::DBI->handler
});

eval {
my $sth = $dbh->prepare("select foo from bar");
$sth->execute;
};

if (my $ex = $@) {
print STDERR "DBI Exception:\n";
print STDERR " Exception Type: ", ref $ex, "\n";
print STDERR " Error: ", $ex->error, "\n";
print STDERR " Err: ", $ex->err, "\n";
print STDERR " Errstr: " $ex->errstr, "\n";
print STDERR " State: ", $ex->state, "\n";
my $ret = $ex->retval;
$ret = 'undef' unless defined $ret;
print STDERR " Return Value: $ret\n";
}

Enjoy!

David

--
David Wheeler AIM: dwTheory
david(at)kineticode(dot)com ICQ: 15726394
Yahoo!: dew7e
Jabber: Theory(at)jabber(dot)org
Kineticode. Setting knowledge in motion.[sm]

In response to

Responses

Browse sfpug by date

  From Date Subject
Next Message elein 2003-02-26 23:05:12 Re: Presentations next meeting?
Previous Message Josh Berkus 2003-02-26 20:55:09 Re: DBD::pg error trapping?