Perl DBI - Error Capture

What is the best way to catch any DBI errors in Perl? For example, if the insertion fails, because the inserted values ​​contained invalid characters, how can I not execute the script to fail, but fix the error and process it accordingly.

I do not want to do "or die" because I do not want to stop the execution of the script.

+8
exception perl error-handling dbi
source share
2 answers

Use the configuration RaiseError=>1 in DBI->connect and wrap your calls in $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 available connection variables.

eg:

 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: $_"; }; 
+12
source share

You can also do the following, which will allow you to die or gracefully handle errors and continue.

 $dbh = DBI->connect($data_src, $user, $pwd) or die $DBI::errstr; my $sth = $dbh->prepare("DELETE FROM table WHERE foo = '?'"); $sth->execute('bar'); if ( $sth->err ) { die "DBI ERROR! : $sth->err : $sth->errstr \n"; } 
+1
source share

All Articles