Re: Catching errors with Perl DBI - Mailing list pgsql-general

From Francisco Olarte
Subject Re: Catching errors with Perl DBI
Date
Msg-id CA+bJJbxj35Sm_duF5R4-t7Ne0U-iCACHp0m6KExRfF-NMKrnGw@mail.gmail.com
Whole thread Raw
In response to Catching errors with Perl DBI  (stan <stanb@panix.com>)
List pgsql-general
Stan:

On Thu, Jul 2, 2020 at 5:03 PM stan <stanb@panix.com> wrote:

> How can I catch the errors generated whne I call an INSERT that violates a
> constraint? I have coded like this:
>
>              my $sth = $dbh->prepare($stmt);
>                          my $rv = $sth->execute() or die $DBI::errstr;
>                          if ( $rv < 0 ) {
>                                  print $DBI::errstr;
>                          }
>
> But, if the INSERT violates a constraint, it never gets the the evaluation
> of the $rv

I assume you mean the if($rv<0) is what it is not executed.

In perl this happens because something died. I assume it is not the
one you coded. This means some of your handles have the RaiseError
attribute, lookit up in the perldoc.

> Is this a setting for the DBI?

I do not remember if it has a global setting, but it sure has a
database handle setting ( which percolates down ). I use it routinely
for easier error handling.

I'm not sure if you know how to from your message, but if something is
dying you can use the block eval construct:

eval {
    # potentially dying code...
       my $sth = $dbh->prepare($stmt);
       my $rv = $sth->execute() or die $DBI::errstr;
       if ( $rv < 0 ) {
              print $DBI::errstr;
        }
     1; # This forces the eval to return true if execution gets here.
} or do {
    # Whatever you want, $@ has the codes.
}

to trap it in perl.

About RaiseError, it is common to set it to true in the handle, put
all your code in a sub() and catch it, in programs where you donot
have easy recovery of errors, and use local eval if needed to catch
this kind of prim. key violation things.

Francisco Olarte.



pgsql-general by date:

Previous
From: Gianni Ceccarelli
Date:
Subject: Re: Catching errors with Perl DBI
Next
From: "David G. Johnston"
Date:
Subject: Re: Different results from identical matviews