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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.