[Dancer-users] Input-validation and Error-Handling in a fun 'dancer' way
Assaf Gordon
gordon at cshl.edu
Wed Sep 14 20:12:25 CEST 2011
Hello Dancers,
I have another dancer-newbie question:
Is there a recommended way to verify input (or general variables) and report errors to the user ?
Common scenario:
I have a form with 3 inputs, and they need to by in a certain format (verifiable by a simple regex).
If the inputs do not conform, I want to:
1. Log the error for later inspection
2. Inform the user (e.g. using Plugin::Dancer::FlashMessage)
(The error message reported to the user is not necessarily the same one written to the log, if I wish to include more technical details in the log, or be more descriptive and verbose to the user).
3. Stop processing the request.
And I wish to do it in the most 'fun' dancer kind of way.
Looking at a naive implementation (below), there's alot of redundant code for validating and reporting the error back to the user (and more validation code than actual processing code).
Any suggestions ?
Thanks!
-gordon
====================
post '/dosomething' => sub {
my $email = params->{email};
my $gene = params->{gene};
my $cutoff = param->{cutoff};
if (!defined $email) {
warning "Missing email address";
flash error => 'Missing email address';
return template 'form_errors' ;
}
elsif (!valid_email($email)) {
warning "Got Invalid email address: $email";
flash error => 'Invalid email address";
return template 'form_errors' ;
}
if (!defined $gene) {
warning "Missing gene identifier";
flash error => 'Missing gene identifier';
return template 'form_errors' ;
}
elsif (!valid_gene_identifier($gene)) {
warning "Got Invalid gene identifier: $gene";
flash error => 'Invalid gene identifier";
return template 'form_errors' ;
}
if (!defined $cutoff) {
warning "Missing cutoff identifier";
flash error => 'Missing cutoff identifier';
return template 'form_errors' ;
}
elsif (!valid_cutoff_value($cutoff)) {
warning "Got Invalid cutoff value: $cutoff";
flash error => 'Invalid Cutoff value: must a value between 0.1 and 0.55';
return template 'form_errors' ;
}
## Input IS OK, do some processing and return the result
my ($result, $error) = process($email, $gene, $cutoff);
template 'result.tt', {
email => $email,
cutoff => $cutoff,
gene => $gene,
result => $result,
error => $error,
};
}
More information about the Dancer-users
mailing list