2009-11-07

Handling Perl DBI errors

Just something I've been working on recently. Previously I would check the result of every DBI statement with RaiseError set and an eval around each statement:



The evals added a lot of repetitive code. DBI database handles have an attribute called HandleError that allows a subroutine to be run when an error is encountered. The code is much cleaner with rollback and confess in the HandleError subroutine.



Also if something different needs to be done with errors for a specific statement the HandleError subroutine can be disabled temporarily by saving it to a temporary variable, setting HandleError to undef, then setting HandleError back to the temporary variable later.