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

I have a wxperl app that calls a DB module I've created but when the DBI module encounters an error it kills my app. Is there a more graceful way of catching errors from the DBI module without dieing? Looking through the docs it seems that setting:
{RaiseError => 0, PrintError => 1}
in the constructor should do that but it is still dieing on me. Is there a better way of inetercepting the error before die is called?

Thanks

Replies are listed 'Best First'.
Re: DBI Error handling
by moritz (Cardinal) on Feb 04, 2009 at 14:54 UTC
    You can wrap the code in an eval{ ... }, and check $@ to see if it succeeded.

    (Update: fixed variable name, toolic++)

      Thanks...I actually think I found the issue. I wasn't doing any error handling after I called my prepare and execute routines so I immediately jumped into my fetch routine without first checking to see if execute was successful. This brings up a question...is it better to define one routine that calls prepare and execute and if successful then call my fetch method. Currently I'm calling prepare/execute for every single query I do.

      Thanks

        Your solution sounds reasonable. However, if you're preparing and executing the same query or a very similar query (like the same fields from the same table with a different value for your when clause) one right after the other then you'll want to be sure you're executing the same prepared statement again. This assumes you're using placeholders. There are many reasons to do that and no reasons not to use them.

        In some applications it's common to issue the same query with different values for the placeholders many times in a row. In some cases, you'd be facing a big headache to keep a prepared query in scope from one use to the next. If it's manageable in your code without a terrible hassle, reusing your prepared statements can really help your database return your data faster and perhaps even with less CPU usage. If you have a busy server or are developing for a hosted environment like a shared web server or a utility cluster (aka "cloud"), it's not just good for your users to get a bit more responsiveness, but it's part of being a good client and member of the community not to use resources from a shared pool that you could easily avoid using.