http://www.perlmonks.org?node_id=437578

svenXY has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

In contrary to all documentation I was capable of, I wasn't able to catch a DBI error to replace it with another message.
I can get the error message into a varialbe, but cannot prevent DBI from displaying the error again.

Here's some sample code:
use DBI; my $dbh = DBI->connect("DBI:mysql:database=www;host=myhost.domain.com: +3306;user=auser;password=apwd", {RaiseError => 1, PrintError => 0}); my $sql = 'select wrong_col, correct_col from table limit 10'; my $hash_ref; print "Trying HandleError (with RaiseError on):\n"; $hashref = $dbh->selectall_hashref($sql, 'filename', {RaiseError => 1, PrintError => 1, HandleError => \&handle_error() +}); print "Trying RaiseError and eval:\n"; eval{ $hashref = $dbh->selectall_hashref($sql, 'filename', {RaiseError => 1, PrintError => 0}); }; if ($@) { print "\tEval found: $@\n"; } my $sth = $dbh->prepare($sql); print "Trying Errstr:\n"; $sth->execute(); if ($dbh->errstr) { print "\tErrstr: " .$dbh->errstr . "\n"; } sub handle_error { # my $error = shift; print "\tSub 'handle_error': $error\n"; print "\tEnd sub\n"; }

As a result, I get:

$ perl tester.pl Trying HandleError (with RaiseError on): Sub 'handle_error': End sub DBD::mysql::db selectall_hashref failed: Unknown column 'wrong_col' in + 'field list' at tester.pl line 11. Trying RaiseError and eval: DBD::mysql::db selectall_hashref failed: Unknown column 'wrong_col' in + 'field list' at tester.pl line 16. Trying Errstr: DBD::mysql::st execute failed: Unknown column 'wrong_col' in 'field li +st' at tester.pl line 26. Errstr: Unknown column 'wrong_col' in 'field list' - or - when redirecting STDERR: $ perl tester.pl 2>/dev/null Trying HandleError (with RaiseError on): Sub 'handle_error': End sub Trying RaiseError and eval: Trying Errstr: Errstr: Unknown column 'wrong_col' in 'field list'

Basically, the error message is printed to STDERR on all three tests, I was never able to prevent it.
Second, the error was caught by handle_error, but the error message was not handed over as it should be.
The third way worked OK, except that it did print the error message to STDERR...

What do I do/think wrong here?
Thanks for any hints,
Sven