FastAPI/Middleware/ExceptionHandler.pm

filter: Statementstmt 97.6% 42 / 43 Branchbran 91.6% 11 / 12 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod 100% 1 / 1 totaltotal 96.8% 61 / 63 CC 8 SCAR 14.2
CC
8
Cov
96%
_dispatch
7.0
handle
2.0
BEGIN
1.0
CRAP 4.2
« FastAPI/Context.pm ↑ Summary FastAPI/Middleware/RateLimit.pm »
1 package PAGI::FastAPI::Middleware::ExceptionHandler;
2  
3 2 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 our $VERSION = qv('v1.7.3');
8 2 our $AUTHORITY = 'cpan:MANWAR';
9  
10 2 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 # Built on the documented add_middleware($coderef) extension point, the
14 # same mechanism eg/rate_limit_demo.pl uses to wrap the app-wide rate
15 # limiter.
16 #
17 # CONTRACT NOTE: the framework's own dependency-failure convention (see
18 # PAGI::FastAPI's _register_route dependency loop) is "set $c->status(>=400)
19 # and return a body hash" rather than throwing a typed exception object. If
20 # your dependencies/handlers already follow that convention, you may not
21 # need this at all. This module exists for the case where you (or a
22 # database layer, or a third-party module you're calling into) throw real
23 # Perl exceptions, blessed objects or plain strings via die, and you want
24 # FastAPI-style "register a handler per exception class" dispatch instead
25 # of wrapping every handler in its own eval.
26  
27 2 class PAGI::FastAPI::Middleware::ExceptionHandler {
28 2 field $handlers :param = {};
29 2 field $default_handler :param = undef;
30  
31 5 ▶ async method handle ($c, $next) {
Subroutine handle: called CC=2 SCAR=6.9
Pod documented
32 5 my $res = eval { return await $next->($c) };
33 5 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 4 1 5
34 4 return await $self->_dispatch($err, $c);
35 }
36 1 return $res;
37 2 }
38  
39 4 ▶ async method _dispatch ($err, $c) {
Subroutine _dispatch: called CC=7 SCAR=19.5
40 4 my $class = blessed($err);
41  
42 4 ▶ if (defined $class) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class) { } 2 2 4
43 # Walk the registered handler classes, most-specific first:
44 # exact class match wins; otherwise the first registered class
45 # that $err->isa(...) matches. Registration order among isa()
46 # matches is significant, register more specific parent classes
47 # AFTER more general ones if that matters to you, since
48 # the first isa() match found wins.
49 2 ▶ if (my $h = $handlers->{$class}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $h = $handlers->{$class}) 1 1 2
50 1 return await $h->($err, $c);
51 }
52 1 for my $registered_class (keys %$handlers) {
53 2 ▶ if ($err->isa($registered_class)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err->isa($registered_class)) 0 2 2
54 0 return await $handlers->{$registered_class}->($err, $c);
55 }
56 }
57 }
58 else {
59 # Plain string exception (die "some message\n"), only a handler
60 # explicitly registered under the empty-string / '' key or the
61 # default handler can catch these, since there's no class to
62 # match against.
63 2 ▶ if (my $h = $handlers->{''}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $h = $handlers->{""}) 1 1 2
64 1 return await $h->($err, $c);
65 }
66 }
67  
68 2 ▶ if ($default_handler) {
Branch: 1 branch
BranchTrueFalseTotal
if ($default_handler) 1 1 2
69 1 return await $default_handler->($err, $c);
70 }
71  
72 # No handler matched and no default configured, re-throw so the
73 # failure isn't silently swallowed. Whatever wraps THIS middleware
74 # (or the PAGI runtime itself) is responsible for turning an
75 # unhandled die into a 500, same as if this middleware weren't
76 # installed at all.
77 1 die $err;
78 2 }
79 }
80  
81 =encoding utf-8
82  
83 =head1 NAME
84  
85 PAGI::FastAPI::Middleware::ExceptionHandler - Typed Exception-to-Handler Dispatch for PAGI::FastAPI
86  
87 =head1 VERSION
88  
89 Version v1.7.3
90  
91 =head1 SYNOPSIS
92  
93 use PAGI::FastAPI::Middleware::ExceptionHandler;
94  
95 package My::Errors::NotFound;
96 sub new ($class, %args) { return bless { %args }, $class }
97 sub message { return $_[0]->{message} // 'Not Found' }
98  
99 package main;
100  
101 my $handler = PAGI::FastAPI::Middleware::ExceptionHandler->new(
102 handlers => {
103 'My::Errors::NotFound' => async sub ($err, $c) {
104 $c->status(404);
105 return { detail => $err->message };
106 },
107 },
108 default_handler => async sub ($err, $c) {
109 $c->status(500);
110 return { detail => 'Internal Server Error' };
111 },
112 );
113  
114 $app->add_middleware(async sub ($c, $next) {
115 return await $handler->handle($c, $next);
116 });
117  
118 $app->get('/items/{id}',
119 handler => async sub ($c) {
120 my $item = My::DB->find($c->path_param('id'))
121 or die My::Errors::NotFound->new(message => 'No such item');
122 return $item;
123 }
124 );
125  
126 =head1 DESCRIPTION
127  
128 Wraps the rest of the middleware/handler chain in an C<eval>, and dispatches
129 any thrown exception to a registered handler based on the exception's class
130 (via C<blessed()> and C<isa()>), falling back to a C<default_handler> if
131 given, or re-throwing if nothing matches.
132  
133 This intentionally mirrors Python FastAPI's C<@app.exception_handler(SomeError)>
134 pattern, adapted to a middleware + registry shape that fits
135 L<PAGI::FastAPI>'s existing C<add_middleware> extension point rather than
136 requiring any change to route registration or dispatch internals.
137  
138 B<Relationship to core's own error convention:> C<PAGI::FastAPI>'s built-in
139 dependency mechanism already has its own failure convention, a dependency
140 sets C<< $c->status(>=400) >> and returns a body hash, which
141 C<PAGI::FastAPI> checks for directly without any exception being thrown at
142 all. This module doesn't replace that; it's for the separate case of actual
143 Perl exceptions (C<die>) escaping a handler or a dependency, which core has
144 no built-in registry for.
145  
146 =head1 METHODS
147  
148 =head2 C<new(%options)>
149  
150 =over 4
151  
152 =item * C<handlers> - HashRef mapping exception class name (string) to a
153 coderef of C<< async sub ($exception, $c) { ... } >>. The empty string key
154 C<''> catches plain (non-blessed) exceptions, e.g. from C<die "message">.
155  
156 =item * C<default_handler> - (Optional) Coderef of the same shape, used when
157 no registered class matches. If omitted, unmatched exceptions are re-thrown.
158  
159 =back
160  
161 =head2 C<handle($c, $next)>
162  
163 Call this from an C<add_middleware> wrapper, exactly as
164 C<eg/rate_limit_demo.pl> does for C<PAGI::FastAPI::Middleware::RateLimit>.
165  
166 =head1 CAVEATS
167  
168 Handler lookup for subclasses (via C<isa()>) iterates the registered
169 handlers in hash order when there's no exact class match, so if an exception
170 could match more than one registered I<parent> class, which one wins is not
171 guaranteed. Register an exact match for any exception class where this
172 ambiguity matters.
173  
174 =head1 SEE ALSO
175  
176 L<PAGI::FastAPI::Middleware::RateLimit>, L<PAGI::FastAPI::Middleware::BotProtection>
177  
178 =head1 AUTHOR
179  
180 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
181  
182 =head1 REPOSITORY
183  
184 L<https://github.com/manwar/PAGI-FastAPI>
185  
186 =head1 BUGS
187  
188 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
189 I will be notified and then you'll automatically be notified of progress on your
190 bug as I make changes.
191  
192 =head1 SUPPORT
193  
194 You can find documentation for this module with the perldoc command.
195  
196 perldoc PAGI::FastAPI::Middleware::ExceptionHandler
197  
198 You can also look for information at:
199  
200 =over 4
201  
202 =item * BUG Report
203  
204 L<https://github.com/manwar/PAGI-FastAPI/issues>
205  
206 =item * Search MetaCPAN
207  
208 L<https://metacpan.org/dist/PAGI-FastAPI/>
209  
210 =back
211  
212 =head1 LICENSE AND COPYRIGHT
213  
214 Copyright (C) 2026 Mohammad Sajid Anwar.
215  
216 This program is free software; you can redistribute it and/or modify it under
217 the terms of the Artistic License (2.0).
218  
219 =cut
220  
221 2 1; # End of PAGI::FastAPI::Middleware::ExceptionHandler
« FastAPI/Context.pm ↑ Summary FastAPI/Middleware/RateLimit.pm »