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

I am actually using "out" parameters to return the error messages and capturing it in the main perl script with the help of func(syb_out_params), but this is for the user defined error messages.. My problem is what about the error messages which will not be handled by the subroutene, take for example "password has expired" while connecting to the database then database connection will not be possible and database will throw its own error.. How to catch these types of errors..
  • Comment on Re^2: Capturing error thrown by a database

Replies are listed 'Best First'.
Re^3: Capturing error thrown by a database
by Marshall (Canon) on Aug 01, 2011 at 11:05 UTC
    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 }
      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.