I'm writing a set of Apache::ASP scripts that comunicate with a MySQL database using DBI. I'm trying to make sure to catch all errors thrown by DBI (or my own code) and issue rollbacks but I find that it'm always learning better techniques. I ended up having three versions of error catching eval/if blocks so I decided I should look for a dynamic solution.
My latest version is the following:
my $dbh = $base::dbh; # get a database handle eval { # lots of inserts, updates, etc... }; if ($@) { my $err = $@; eval { $dbh->rollback }; # display formatted errors $base::showerrors( ($base::debug ? $err : "database related error"), ($@ ? " error performing rollback\n" : " rollback performed successfully\n") ); }
I have now come up with the following solution. I declare a couple of subs at the server startup (in global.asa)
sub dbtry (&@) { my ($dbtry, $dbcatch) = @_; local $dbh = $base::dbh; eval { local $_ = $dbh; &$dbtry }; if($@) { local $_ = "dbcaught:"; chomp $@; $_ .= ($base::debug) ? " $@" : " database related error"; eval { $dbh->rollback }; $_ .= ($@ ? " Error Performing Rollback\n" : " Rollback Performed Successfully\n"); &$dbcatch; } } sub dbcatch (&) { $_[0] }
Then I use the following (less cluttered) code to get a job done.
dbtry { # lots of inserts, updates, etc... } dbcatch { $base::showerrors("error: $_"); }
I'm also thinking about merging other error logging mechanisims I use in this code. I've never used this code in practice -- and I'm not entirely convinced that it's the best way to go. Can anyone see anything wrong with this code ? Does anyone know how to improve it ? Any experiences with similar techniques ?
In reply to Catching what DBI throws by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |