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

I'm thinking of developing a web app with Class:DBI. All is well but I think I'm missing something simple.

I would like to use constraints to do data validation.
Seems simple enough, problem is, constraint failures die. I don't want this so I override _croak. But, then what?
I would like to catch the error, but on returning from my _croak Class::DBI still sets the bad value.

From the Class::DBI docs

When using this mechanism for form data validation, for example, this exception data can be stored in an exception object, via a custom _croak() method, and then caught and used to redisplay the form with error messages next to each field which failed validation.

So I know it can be done, but I'm not sure I see how.

Replies are listed 'Best First'.
Re: Class::DBI _croak
by perrin (Chancellor) on May 16, 2005 at 22:44 UTC
    Wrap the method call to Class::DBI in an eval and catch the exception. Then use the exception object to figure out what to tell the user.
Re: Class::DBI _croak
by cbrandtbuffalo (Deacon) on May 17, 2005 at 16:07 UTC
    As [id://perrin] mentioned, eval is the easiest way to catch these so the user doesn't see a nasty error. However, it might start to seem tedious to put eval blocks around all of your Class::DBI code.

    This type of problem is one of the reasons several web app frameworks have popped up on CPAN. CGI::Prototyped, for example, wraps all of the main execution block in an eval. This allows you to build a single error handling sub that knows how to handle the error and display a nice page for the user. This solves the problem not only for Class::DBI 'dies' but allows you to use die throughout your code as a exception.

    If you don't want to get into learning a web app framework, you could just steal the idea and put your eval at a high enough level that it catches everything that might die.