#!/usr/bin/perl use strict; use warnings; use DBI; my $dbh = DBI->connect("DBI:mysql:database=test;user=auser;password=apwd", {RaiseError => 1, PrintError => 1}); # set up error handling $dbh->{HandleError} = sub { handle_error(@_) }; my $sql = 'select wrong_col, correct_col from test limit 10'; our $handle_it; # This is only needed for this contrived example for $handle_it ( 0 .. 1 ) { print "\n", "-" x 40, "\n\n" if $handle_it; print "Trying HandleError (with RaiseError on):\n"; print "handle it? ", ($handle_it) ? 'yes' : 'no', "\n"; my $hashref = $dbh->selectall_hashref($sql, 'filename'); print "$_\t-->\t$hashref->{$_}\n" for (keys %{$hashref}); print "errstr says: ", $dbh->errstr, "\n" if $dbh->errstr; } sub handle_error { my ($error, $dbh) = @_; my $handled = 0; # did we handle the error? print "\n\tSub 'handle_error': $error\n"; if ( $handle_it ) { # if you want to say this error is not an error # clear the error $dbh->set_err(undef,undef); # set the new return value $_[2] = { wrong_col => 'bar', correct_col => 'foo' }; # update our handled flag $handled = 1; } else { # we acknowledge it was an error # muck around with $error here and store it in $_[0] # $_[0] is the error message seen by RaiseError/PrintError $_[0] = 'The gremlins are loose again!'; # potentially change the error too $dbh->set_err(1234, $_[0]); } print "\tEnd sub\n\n"; # return our handled flag return $handled; } __END__ Trying HandleError (with RaiseError on): handle it? no Sub 'handle_error': DBD::mysql::db selectall_hashref failed: Table 'test .test' doesn't exist End sub The gremlins are loose again! at ./database.pl line 24. errstr says: Table 'test.test' doesn't exist [err was 1146 now 1234] The gremlins are loose again! ---------------------------------------- Trying HandleError (with RaiseError on): handle it? yes Sub 'handle_error': DBD::mysql::db selectall_hashref failed: Table 'test .test' doesn't exist End sub correct_col --> foo wrong_col --> bar