blib/lib/PAGI/Middleware/ErrorHandler.pm untested

filter: Statementstmt 0.0% 0 / 89 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 22 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 153 CC 14 SCAR 37.2
CC
14
Cov
0%
_generate_error_body
72.0
wrap
56.0
_init
2.0
CRAP 41.1
1 package PAGI::Middleware::ErrorHandler;
2 $PAGI::Middleware::ErrorHandler::VERSION = '0.002001';
3 use strict;
4 use warnings;
5 use parent 'PAGI::Middleware';
6 use Future::AsyncAwait;
7 use Scalar::Util 'blessed';
8  
9 =head1 NAME
10  
11 PAGI::Middleware::ErrorHandler - Exception handling middleware
12  
13 =head1 SYNOPSIS
14  
15 use PAGI::Middleware::Builder;
16  
17 my $app = builder {
18 enable 'ErrorHandler',
19 development => 1,
20 on_error => sub {
21 my ($error) = @_; warn "App error: $error" };
22 $my_app;
23 };
24  
25 =head1 DESCRIPTION
26  
27 PAGI::Middleware::ErrorHandler catches exceptions thrown by the inner
28 application and converts them to appropriate HTTP error responses.
29  
30 =head1 CONFIGURATION
31  
32 =over 4
33  
34 =item * development (default: 0)
35  
36 If true, include stack trace in error responses. Should be false in production.
37  
38 =item * on_error (default: undef)
39  
40 Callback invoked with the error when an exception is caught. Useful for logging.
41  
42 on_error => sub {
43 my ($error) = @_; $logger->error($error) }
44  
45 =item * content_type (default: 'text/html')
46  
47 Content type for error responses. Supported: 'text/html', 'application/json', 'text/plain'
48  
49 =item * status (default: 500)
50  
51 HTTP status code for general exceptions.
52  
53 =back
54  
55 =cut
56  
57 sub _init {
58 my ($self, $config) = @_;
59  
60 $self->{development} = $config->{development} // 0;
61 $self->{on_error} = $config->{on_error};
62 $self->{content_type} = $config->{content_type} // 'text/html';
63 $self->{status} = $config->{status} // 500;
64 }
65  
66 sub wrap {
67 my ($self, $app) = @_;
68  
69 return async sub {
70 my ($scope, $receive, $send) = @_;
71 # Only handle HTTP requests
72 if ($scope->{type} ne 'http') {
73 await $app->($scope, $receive, $send);
74 return;
75 }
76  
77 my $response_started = 0;
78  
79 # Intercept send to track if response has started
80 my $wrapped_send = async sub {
81 my ($event) = @_;
82 if ($event->{type} eq 'http.response.start') {
83 $response_started = 1;
84 }
85 await $send->($event);
86 };
87  
88 # Try to run the app
89 my $error;
90 eval {
91 await $app->($scope, $receive, $wrapped_send);
92 1;
93 } or do {
94 $error = $@ || 'Unknown error';
95 };
96  
97 # Handle error if one occurred
98 if ($error) {
99 # Call on_error callback if provided
100 if ($self->{on_error}) {
101 eval { $self->{on_error}->($error) };
102 }
103  
104 # If response already started, we can't send error page
105 if ($response_started) {
106 # Best we can do is log and close
107 warn "Error occurred after response started: $error\n";
108 return;
109 }
110  
111 # Determine status code
112 my $status = $self->{status};
113  
114 # Check for specific exception types
115 if (blessed($error) && $error->can('status_code')) {
116 $status = $error->status_code;
117 }
118  
119 # Generate error response
120 my ($body, $content_type) = $self->_generate_error_body($error, $status);
121  
122 await $send->({
123 type => 'http.response.start',
124 status => $status,
125 headers => [
126 ['content-type', $content_type],
127 ['content-length', length($body)],
128 ],
129 });
130  
131 await $send->({
132 type => 'http.response.body',
133 body => $body,
134 more => 0,
135 });
136 }
137 };
138 }
139  
140 sub _generate_error_body {
141 my ($self, $error, $status) = @_;
142  
143 my $error_text = "$error";
144 my $content_type = $self->{content_type};
145  
146 # Clean up error for display
147 my $display_error = $error_text;
148 unless ($self->{development}) {
149 # In production, don't reveal internal details
150 $display_error = $self->_status_message($status);
151 }
152  
153 if ($content_type eq 'application/json') {
154 require JSON::MaybeXS;
155 my $body = JSON::MaybeXS::encode_json({
156 error => $display_error,
157 status => $status,
158 ($self->{development} ? (stack => $error_text) : ()),
159 });
160 return ($body, 'application/json');
161 }
162 elsif ($content_type eq 'text/plain') {
163 my $body = "Error $status: $display_error";
164 if ($self->{development} && $error_text ne $display_error) {
165 $body .= "\n\nStack trace:\n$error_text";
166 }
167 return ($body, 'text/plain; charset=utf-8');
168 }
169 else {
170 # Default to HTML
171 my $safe_error = $self->_html_escape($display_error);
172 my $safe_stack = $self->{development} ? $self->_html_escape($error_text) : '';
173  
174 my $body = <<"HTML";
175 <!DOCTYPE html>
176 <html>
177 <head>
178 <title>Error $status</title>
179 <style>
180 body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; margin: 40px; }
181 h1 { color: #c00; }
182 .error { background: #fee; padding: 20px; border-radius: 4px; margin: 20px 0; }
183 pre { background: #f4f4f4; padding: 15px; overflow-x: auto; border-radius: 4px; }
184 </style>
185 </head>
186 <body>
187 <h1>Error $status</h1>
188 <div class="error">$safe_error</div>
189 HTML
190  
191 if ($self->{development} && $safe_stack) {
192 $body .= " <h2>Stack Trace</h2>\n <pre>$safe_stack</pre>\n";
193 }
194  
195 $body .= "</body>\n</html>\n";
196  
197 return ($body, 'text/html; charset=utf-8');
198 }
199 }
200  
201 sub _html_escape {
202 my ($self, $text) = @_;
203  
204 $text =~ s/&/&amp;/g;
205 $text =~ s/</&lt;/g;
206 $text =~ s/>/&gt;/g;
207 $text =~ s/"/&quot;/g;
208 return $text;
209 }
210  
211 sub _status_message {
212 my ($self, $status) = @_;
213  
214 my %messages = (
215 400 => 'Bad Request',
216 401 => 'Unauthorized',
217 403 => 'Forbidden',
218 404 => 'Not Found',
219 405 => 'Method Not Allowed',
220 408 => 'Request Timeout',
221 413 => 'Payload Too Large',
222 429 => 'Too Many Requests',
223 500 => 'Internal Server Error',
224 502 => 'Bad Gateway',
225 503 => 'Service Unavailable',
226 504 => 'Gateway Timeout',
227 );
228 return $messages{$status} // 'Error';
229 }
230  
231 1;
232  
233 __END__