Re: Catching errors with Perl DBI

From: Gianni Ceccarelli <dakkar(at)thenautilus(dot)net>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Catching errors with Perl DBI
Date: 2020-07-02 15:17:22
Message-ID: 20200702161722.340d4fce@exelion
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, 2 Jul 2020 11:03:37 -0400
stan <stanb(at)panix(dot)com> wrote:

> my $sth = $dbh->prepare($stmt);
> my $rv = $sth->execute() or die $DBI::errstr;

that ``or die`` means: if the result of the ``execute`` is false
(which only happens on error), throw an exception (which, as you
noticed, terminates the process unless caught with an ``eval {}`` or
similar construct)

> if ( $rv < 0 ) { print $DBI::errstr; }

Notice that ``$rv`` would never be less than 0: for an ``INSERT``,
it's the number of rows inserted (or a special "0 but true" value in
case no rows were inserted).

So, you can do two things:

* keeping the same style::

my $rv = $sth->execute(@bind_values);
if (!$rv) {
print $sth->errstr;
# and probably do something useful here ☺
}

* switching to exceptions everywhere

Tell DBI you want exceptions::

my $dbh = DBI->connect(
$dsn,$user,$password,
{
PrintError => 0,
RaiseErorr => 1,
PrintWarn => 0,
RaiseWarn => 1,
}
);

then run statements like this::

eval { $dbh->prepare($stmt)->execute(@bind_values) }
or do {
print $@; # the exception is store in this variable
};

--
Dakkar - <Mobilis in mobile>
GPG public key fingerprint = A071 E618 DD2C 5901 9574
6FE2 40EA 9883 7519 3F88
key id = 0x75193F88

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Francisco Olarte 2020-07-02 15:18:14 Re: Catching errors with Perl DBI
Previous Message Anders Steinlein 2020-07-02 15:06:24 Re: Different results from identical matviews