Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

Basically, there are two ways of handling database errors, check (almost) every DBI call for errors or set 'RaiseError' attribute to '1ยด:

-- Manual checking

This way, you have to add code yourself to check for database error conditions, so after nearly every method call you should check if the operation completed successfully.

There are two DBI methods that are very helpful to manually check for database errors: 'err' and 'errstr'.

'err' returns the native database engine error code from the last DBI method called. The code returned is usually an integer.

'errstr' returns the native database engine error message from the last DBI method called.

Example:

$dbh = DBI->connect($data_src, $user, $pwd) or die $DBI::errstr;
 
my $sth = $dbh->prepare("DELETE FROM table WHERE count < '?'");
$sth->execute(25);
if ( $sth->err )
{
  die "ERROR! return code: . $sth->err . " error msg: " . $sth->errstr . "\n";
}

-- Setting 'RaiseError' attribute

If DBI 'RaiseError' attribute is set to '1' (is '0' by default), then any database error will cause the DBI module to 'die' with an appropriate message.

When using 'RaiseError', is recommended to set the 'PrintError' atribute to '0')

Example:

my $dbh = DBI->connect($dsn, $user, $pw, { RaiseError => 1, PrintError => 0 });


You can also provide a

You can also provide a custom sub to handle errors with the RaiseError flag set.
After establishing server connection:

$dbh->{HandleError} = sub {
my $error = shift;
# do something with error...;
};

Or in attributes:

my $dbh = DBI->connect("DBI:......, { RaiseError => 1, HandleError => \&DBerror })|| die $DBI::errstr;

sub DBerror {
my $error = shift;
# do something with error...
}

etc...

Only disadvantage is knowing what line the error originated from in your script.

--------
I'm unique just like everyone else!