Error Handling

From Dreamwidth Notes
Jump to: navigation, search

We have a zillion ways of including errors, and each time someone writes a new page they have to look back at older examples and decide which (among the many) to follow for this page. So to simplify things, here's the canonical error-handling pattern for controllers:

In cgi-bin/DW/Controller/

# 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 to be printed on the page
        errors => $errors,
        # the data in the form elements on page load
        #     if we posted (but had errors), then this will have the user-submitted values automatically
        #     if we didn't post, then it will load with the default values you gave
        formdata => $r->post_args || { some_form_field => "defaultvalue" },
    return DW::Template->render_template( "", $vars );

In views/

   .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 -%]