FU: Throw and handle FU::Validate errors directly

Instead of wrapping them in a FU::err that isn't easily inspected.
This commit is contained in:
Yorhel 2025-04-20 18:37:54 +02:00
parent 1594006739
commit ea8ad9e483

22
FU.pm
View file

@ -300,13 +300,13 @@ sub _read_req($c) {
}
sub _is_done($e) { ref $@ eq 'FU::err' && $@->[0] == 200 }
sub _is_done($e) { ref $e eq 'FU::err' && $e->[0] == 200 }
sub _log_err($e) {
return if !$e;
return if !debug && ref $@ eq 'FU::err' && $@->[0] != 500;
if (!$REQ->{full_err} && (ref $@ ne 'FU::err' || $@->[0] == 500)) {
$REQ->{full_err}++;
my $crit = $e isa 'FU::err' ? $e->[0] == 500 : !($e isa 'FU::Validate::err');
return if !debug && !$crit;
if ($crit && !$REQ->{full_err}++) {
$e =~ s/^\s+//;
$e =~ s/\s+$//;
log_write join "\n",
@ -377,7 +377,7 @@ sub _do_req($c) {
}
if ($err) {
my($code, $msg) = ref $err eq 'FU::err' ? $err->@* : (500, $err);
my($code, $msg) = $err isa 'FU::err' ? @$err : $err isa 'FU::Validate::err' ? (400, $err) : (500, $err);
fu->reset;
fu->status($code);
my $ok = eval { ($onerr{$code} || $onerr{500})->($code, $msg) };
@ -642,8 +642,7 @@ sub _getfield($data, @a) {
return $data->{$a[0]};
}
my $schema = FU::Validate->compile(@a > 1 ? { keys => {@a} } : $a[0]);
my $res = eval { $schema->validate($data) };
fu->error(400, "Input validation failed: $@") if $@;
my $res = $schema->validate($data);
return @a == 2 ? $res->{$a[0]} : $res;
}
@ -1209,6 +1208,12 @@ for a certain error code, C<500> is used as fallback.
=back
All of the above C<$sub> callbacks are allowed to throw an error. Special
handling is given to exceptions generated by C<< fu->error() >>, which are
relegated to the appropriate C<on_error> handler, and errors thrown by the
C<validate()> method of L<FU::Validate>, which result in the C<400> error
handler being run. Any other exception is passed to the C<500> error handler.
=head1 The 'fu' Object
@ -1303,8 +1308,7 @@ methods below to reliably handle all sorts of query strings.
=item fu->query($name => $schema)
Parse, validate and return the query parameter identified by C<$name> with the
given L<FU::Validate> schema. Calls C<< fu->error(400) >> with a useful error
message if validation fails.
given L<FU::Validate> schema.
To fetch a query parameter that may have multiple values, use: