Difference between revisions of "Error Handling"

From Dreamwidth Notes
Jump to: navigation, search
(Created page with "Error handling within controllers We have a zillion ways of including errors, and each time I've written a new page I've had to look back at older examples and decide which (...")
(No difference)

Revision as of 08:28, 12 July 2014

Error handling within controllers

We have a zillion ways of including errors, and each time I've written a new page I've had to look back at older examples and decide which (among the many) to follow for this page. So to simplify things, I've written a DW::FormErrors module which aims to make error handling standard and simple.

Here is the bare-bones example of what to do.

In cgi-bin/DW/Controller/SomeController.pm:


# import the module
use DW::FormErrors;
 
...
 
sub some_handler {
    my $r = DW::Request->get;
    ...
    # create a new DW::FormErrors object
    my $errors = DW::FormErrors->new;
    if ( $r->did_post ) {
        # add errors that are relevant
        $errors->add( "form_field_name", ".error.ml_string" ) if $condition;
        $errors->add( "form_field_name", ".error.ml_string_with_arguments", { key => $value } ) if $condition;
 
        unless ( $errors->exist ) {
            # process the POSTed information if we didn't have any errors
        }
    }
 
    ...
 
    my $vars = {
        errors => $errors,
    }
    return DW::Template->render_template( "someview.tt", $vars );
}

In views/someview.tt.text:

   .error.ml_string=Error message
   .error.ml_string_with_arguments=Error message with [[key]]

On pages that use Foundation (newer pages, or newly converted pages), the errors will be displayed automatically in two places: at the top of the screen, and near the form field with name="form_field_name" (if there is one).


If you need to include the errors manually for any reason (though you really shouldn't!), you can display the errors by putting this at the top of your file in views/*.tt:

   [%- PROCESS block.errors -%]