Perl DBI - Capturing errors

Chris picture Chris · Jan 28, 2011 · Viewed 17.6k times · Source

What's the best way of capturing any DBI errors in Perl? For example if an insert fails because there were illegal characters in the values being inserted, how can I not have the script fail, but capture the error and handle it appropriately.

I don't want to do the "or die" because I don't want to stop execution of the script.

Answer

Ether picture Ether · Jan 28, 2011

Use the RaiseError=>1 configuration in DBI->connect, and wrap your calls to the $dbh and $sth in a try block (TryCatch and Try::Tiny are good implementations for try blocks).

See the docs for more information on other connect variables available.

for example:

use strict;
use warnings;

use DBI;
use Try::Tiny;

my $dbh = DBI->connect(
    $your_dsn_here,
    $user,
    $password,
    {
        PrintError => 0,
        PrintWarn  => 1,
        RaiseError => 1,
        AutoCommit => 1,
    }
);
try
{
    # deliberate typo in query here
    my $data = $dbh->selectall_arrayref('SOHW TABLES', {});
}
catch
{
    warn "got dbi error: $_";
};