From ea8ad9e4838e75b149a357388f94ca34e7a0eca9 Mon Sep 17 00:00:00 2001 From: Yorhel Date: Sun, 20 Apr 2025 18:37:54 +0200 Subject: [PATCH] FU: Throw and handle FU::Validate errors directly Instead of wrapping them in a FU::err that isn't easily inspected. --- FU.pm | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/FU.pm b/FU.pm index 6a9ec47..0161f01 100644 --- a/FU.pm +++ b/FU.pm @@ -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 handler, and errors thrown by the +C method of L, 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 schema. Calls C<< fu->error(400) >> with a useful error -message if validation fails. +given L schema. To fetch a query parameter that may have multiple values, use: