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

Monks,

I'm trying to understand how to catch errors in Class::DBI. For clarity's sake, consider that I am trying to violate a unique constraint. Thus the DB will cause a call to _croak as described in the docs:

The _croak() method is passed an error message and in some cases some extra information as described below. The default behaviour is simply to call Carp::croak($message). Applications that require custom behaviour should override the _croak() method in their application base class (or table classes for table-specific behaviour). For example: use Error; sub _croak { my ($self, $message, %info) = @_; # convert errors into exception objects # except for duplicate insert errors which we'll ignore Error->throw(-text => $message, %info) unless $message =~ /^Can't insert .* duplicate/; return; }

What I'm missing (and my question is) how do I 'catch' these DB errors in my main code where I 'tried' to do the DB insert?

The DB insert looks like this:

... various Class::DBI stuff not included... $entry = Contacts->create( \%hash );

-------------------------------------
Nothing is too wonderful to be true
-- Michael Faraday

Replies are listed 'Best First'.
Re: Catching errors with Class::DBI
by shenme (Priest) on Nov 12, 2003 at 00:58 UTC
    I think the answer is "just like any exception".
    eval { $entry = Contacts->create( \%hash ); }; if( $@ ) { ... handle the exception from CDBI or passed upwards by ... ... CDBI as mentioned in last two paras under EXCEPTIONS ... }

      Exceptions can also be handled via the DBI HandleError attribute. Config::DBI's docs shows an example of setting one up.

      Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality

(z) Re: Catching errors with Class::DBI
by zigdon (Deacon) on Nov 12, 2003 at 21:47 UTC

    Sounds like (and I haven't tried this myself) you should add an _croak method to your parent CDBI class - so in the Music example, you'd add a _croak to Music::DBI.

    Does that make sense?

    -- zigdon