in reply to Re^2: Capturing error thrown by a database
in thread Capturing error thrown by a database

When the DBI has an error, it is available as the string provided by DBI->errstr. So for example in a wild guess at your subroutine below, if the connection fails (no handle returned), the sub returns the DBI->errstr. Of course your calling program would have to do something with that. PrintError=1 causes warning message to be printed, you may or may not want that. RaiseError=1 is a bit stronger and causes a "die", which you don't want unless you inside of a block eval.

You can set RaiseError =1 and put statements in an eval{} which in this context would be Perl's equivalent of a try/catch. In the case of failure, again, calling the errstr method of the DBI will give you its error.

my $dbh; sub connectsybase { my ($var1, $var2,...) = @_; $dbh = DBI->connect($data_source, $username, $auth, {printError => 1} ); return (DBI->errstr) if (!dbh); # fail return ""; # success, NULL string }

Replies are listed 'Best First'.
Re^4: Capturing error thrown by a database
by puneet.keswani (Novice) on Aug 01, 2011 at 12:53 UTC
    Hi Marshall.. The example which you have given is working fine.. i am extremely thankfull to you for that, but I am using the RaiseError=1 attribute, which causes a die, inside an eval.. Can you give an example similar to above using RaiseError=1.. Thanks a lot..
      You just check and see if $@ gets set after the eval block. See eval doc page

      eval { some db command $dbh->do....; } if ($@) { print "$@\n"; print $DBI::Errstr,"\n"; }
      do some experimenting, $@ may be same as the dbi's error string if PrintError =1.
        Hey Marshall.. I have already tried that.. I am pasting here the code snippet. Please advise.. eval { sub OpenSybaseConnection { my ($srv, $user, $pwd, $db) = @_; my $dbh; $FH1=$_4; print $FH1 "\n\nConnected to Server:$srv, Database:$db\n"; $dbh=DBI->connect("dbi:Sybase:server=$srv", $user, $pwd,{RaiseError =>1,PrintError =>1 }) || die $DBI::errstr; $dbh->do("use $db"); $common::conn_hdl = $dbh; }; }; if($@) { @proc_error=$@ ; print "inside if\n"; print "Check for if\n"; print "Hi:$@"; print "\nIn Common: @proc_error: HELP"; }