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

From Gianni Ceccarelli
Subject Re: Catching errors with Perl DBI
Date
Msg-id 20200702161722.340d4fce@exelion
Whole thread Raw
In response to Catching errors with Perl DBI  (stan <stanb@panix.com>)
List pgsql-general
On Thu, 2 Jul 2020 11:03:37 -0400
stan <stanb@panix.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




pgsql-general by date:

Previous
From: Anders Steinlein
Date:
Subject: Re: Different results from identical matviews
Next
From: Francisco Olarte
Date:
Subject: Re: Catching errors with Perl DBI