Re: Catching errors with Perl DBI

Поиск
Список
Период
Сортировка
От Gianni Ceccarelli
Тема Re: Catching errors with Perl DBI
Дата
Msg-id 20200702161722.340d4fce@exelion
обсуждение исходный текст
Ответ на Catching errors with Perl DBI  (stan <stanb@panix.com>)
Список 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 по дате отправления:

Предыдущее
От: Anders Steinlein
Дата:
Сообщение: Re: Different results from identical matviews
Следующее
От: Francisco Olarte
Дата:
Сообщение: Re: Catching errors with Perl DBI