Debian Codegraph @

lib/Dancer2/Core/Error.pm

raw
1 package Dancer2::Core::Error;
2 # ABSTRACT: Class representing fatal errors
3 $Dancer2::Core::Error::VERSION = '2.2.2';
4 use Moo;
5 use Carp;
6 use Dancer2::Core::Types;
7 use Dancer2::Core::MIME;
8 use Dancer2::Core::HTTP;
9 use Data::Dumper;
10 use Path::Tiny ();
11 use Sub::Quote;
12 use Module::Runtime qw/ require_module use_module /;
13 use Ref::Util qw< is_hashref >;
14 use Clone qw(clone);
15
16 has app => (
17 is => 'ro',
18 isa => InstanceOf['Dancer2::Core::App'],
19 predicate => 'has_app',
20 );
21
22 has show_stacktrace => (
23 is => 'ro',
24 isa => Bool,
25 default => sub {
26 my $self = shift;
27
28 $self->has_app
29 and return $self->app->setting('show_stacktrace');
30 },
31 );
32
33 has charset => (
34 is => 'ro',
35 isa => Str,
36 default => sub {'UTF-8'},
37 );
38
39 has type => (
40 is => 'ro',
41 isa => Str,
42 default => sub {'Runtime Error'},
43 );
44
45 has title => (
46 is => 'ro',
47 isa => Str,
48 lazy => 1,
49 builder => '_build_title',
50 );
51
52 has censor => (
53 is => 'ro',
54 isa => CodeRef,
55 lazy => 1,
56 default => sub {
57 my $self = shift;
58
59 if( my $custom = $self->has_app && $self->app->setting('error_censor') ) {
60
61 if( is_hashref $custom ) {
62 die "only one key can be set for the 'error_censor' setting\n"
63 if 1 != keys %$custom;
64
65 my( $class, $args ) = %$custom;
66
67 my $censor = use_module($class)->new(%$args);
68
69 return sub {
70 $censor->censor(@_);
71 }
72 }
73
74 my $coderef = eval '\&'.$custom;
75
76 # it's already defined? Nice! We're done
77 return $coderef if $coderef;
78
79 my $module = $custom =~ s/::[^:]*?$//r;
80
81 require_module($module);
82
83 return eval '\&'.$custom;
84 }
85
86 # reminder: update POD below if changing the config here
87 my $data_censor = use_module('Data::Censor')->new(
88 sensitive_fields => qr/pass|card.?num|pan|secret/i,
89 replacement => "Hidden (looks potentially sensitive)",
90 );
91
92 return sub {
93 $data_censor->censor(@_);
94 };
95 }
96 );
97
98 sub _build_title {
99 my ($self) = @_;
100 my $title = 'Error ' . $self->status;
101 if ( my $msg = Dancer2::Core::HTTP->status_message($self->status) ) {
102 $title .= ' - ' . $msg;
103 }
104
105 return $title;
106 }
107
108 has template => (
109 is => 'ro',
110 lazy => 1,
111 builder => '_build_error_template',
112 );
113
114 sub _build_error_template {
115 my ($self) = @_;
116
117 # look for a template named after the status number.
118 # E.g.: views/404.tt for a TT template
119 my $engine = $self->app->template_engine;
120 return $self->status
121 if $engine->pathname_exists( $engine->view_pathname( $self->status ) );
122
123 return;
124 }
125
126 has static_page => (
127 is => 'ro',
128 lazy => 1,
129 builder => '_build_static_page',
130 );
131
132 sub _build_static_page {
133 my ($self) = @_;
134
135 # TODO there must be a better way to get it
136 my $public_dir = $ENV{DANCER_PUBLIC}
137 || ( $self->has_app && $self->app->config->{public_dir} );
138
139 return if !$public_dir;
140
141 my $file = Path::Tiny::path($public_dir)->child( $self->status . '.html' );
142 return if !$file->is_file;
143
144 return eval { $file->slurp_utf8 };
145 }
146
147 sub default_error_page {
148 my $self = shift;
149
150 require_module('Template::Tiny');
151
152 my $uri_base = $self->has_app && $self->app->has_request ?
153 $self->app->request->uri_base : '';
154
155 # GH#1001 stack trace if show_stacktrace is true and this is a 'server' error (5xx)
156 my $show_fullmsg = $self->show_stacktrace && $self->status =~ /^5/;
157 my $opts = {
158 title => $self->title,
159 charset => $self->charset,
160 content => $show_fullmsg ? $self->full_message : _html_encode($self->message) || 'Wooops, something went wrong',
161 uri_base => $uri_base,
162 };
163
164 Template::Tiny->new->process( \<<"END_TEMPLATE", $opts, \my $output );
165 <!DOCTYPE html>
166 <html lang="en">
167 <head>
168 <meta charset="[% charset %]">
169 <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
170 <title>[% title %]</title>
171 <link rel="stylesheet" href="[% uri_base %]/css/error.css">
172 </head>
173 <body>
174 <h1>[% title %]</h1>
175 <div id="content">
176 [% content %]
177 </div>
178 </body>
179 </html>
180 END_TEMPLATE
181
182 return $output;
183 }
184
185 # status and message are 'rw' to permit modification in core.error.before hooks
186 has status => (
187 is => 'rw',
188 default => sub {500},
189 isa => Num,
190 );
191
192 has message => (
193 is => 'rw',
194 isa => Str,
195 lazy => 1,
196 default => sub { '' },
197 );
198
199 sub full_message {
200 my ($self) = @_;
201 my $html_output = "<h2>" . $self->type . "</h2>";
202 $html_output .= $self->backtrace;
203 $html_output .= $self->environment;
204 return $html_output;
205 }
206
207 has serializer => (
208 is => 'ro',
209 isa => Maybe[ConsumerOf['Dancer2::Core::Role::Serializer']],
210 builder => '_build_serializer',
211 );
212
213 sub _build_serializer {
214 my ($self) = @_;
215
216 $self->has_app && $self->app->has_serializer_engine
217 and return $self->app->serializer_engine;
218
219 return;
220 }
221
222 sub BUILD {
223 my ($self) = @_;
224
225 $self->has_app &&
226 $self->app->execute_hook( 'core.error.init', $self );
227 }
228
229 has exception => (
230 is => 'ro',
231 isa => Str,
232 predicate => 1,
233 coerce => sub {
234 # Until we properly support exception objects, we shouldn't barf on
235 # them because that hides the actual error, if object overloads "",
236 # which most exception objects do, this will result in a nicer string.
237 # other references will produce a meaningless error, but that is
238 # better than a meaningless stacktrace
239 return "$_[0]"
240 }
241 );
242
243 has response => (
244 is => 'rw',
245 lazy => 1,
246 default => sub {
247 my $self = shift;
248 my $serializer = $self->serializer;
249 # include server tokens in response ?
250 my $no_server_tokens = $self->has_app
251 ? $self->app->config->{'no_server_tokens'}
252 : defined $ENV{DANCER_NO_SERVER_TOKENS}
253 ? $ENV{DANCER_NO_SERVER_TOKENS}
254 : 0;
255 return Dancer2::Core::Response->new(
256 mime_type => $self->has_app ? $self->app->mime_type : Dancer2::Core::MIME->new(),
257 server_tokens => !$no_server_tokens,
258 ( serializer => $serializer )x!! $serializer
259 );
260 }
261 );
262
263 has content_type => (
264 is => 'ro',
265 lazy => 1,
266 default => sub {
267 my $self = shift;
268 $self->serializer
269 ? $self->serializer->content_type
270 : 'text/html'
271 },
272 );
273
274 has content => (
275 is => 'ro',
276 lazy => 1,
277 builder => '_build_content',
278 );
279
280 sub _build_content {
281 my $self = shift;
282
283 # return a hashref if a serializer is available
284 if ( $self->serializer ) {
285 my $content = {
286 message => $self->message,
287 title => $self->title,
288 status => $self->status,
289 };
290 $content->{exception} = $self->exception
291 if $self->has_exception;
292 return $content;
293 }
294
295 # otherwise we check for a template, for a static file,
296 # for configured error_template, and, if all else fails,
297 # the default error page
298 if ( $self->has_app and $self->template ) {
299 # Render the template using apps' template engine.
300 # This may well be what caused the initial error, in which
301 # case we fall back to static page if any error was thrown.
302 # Note: this calls before/after render hooks.
303 my $content = eval {
304 $self->app->template(
305 $self->template,
306 { title => $self->title,
307 content => $self->message,
308 exception => $self->exception,
309 status => $self->status,
310 }
311 );
312 };
313 $@ && $self->app->engine('logger')->log( warning => $@ );
314
315 # return rendered content unless there was an error.
316 return $content if defined $content;
317 }
318
319 # It doesn't make sense to return a static page for a 500 if show_stacktrace is on
320 if ( !($self->show_stacktrace && $self->status eq '500') ) {
321 if ( my $content = $self->static_page ) {
322 return $content;
323 }
324 }
325
326 if ($self->has_app && $self->app->config->{error_template}) {
327 my $content = eval {
328 $self->app->template(
329 $self->app->config->{error_template},
330 { title => $self->title,
331 content => $self->message,
332 exception => $self->exception,
333 status => $self->status,
334 }
335 );
336 };
337 $@ && $self->app->engine('logger')->log( warning => $@ );
338
339 # return rendered content unless there was an error.
340 return $content if defined $content;
341 }
342
343 return $self->default_error_page;
344 }
345
346 sub throw {
347 my $self = shift;
348 $self->response(shift) if @_;
349
350 $self->response
351 or croak "error has no response to throw at";
352
353 $self->has_app &&
354 $self->app->execute_hook( 'core.error.before', $self );
355
356 my $message = $self->content;
357
358 $self->response->status( $self->status );
359 $self->response->content_type( $self->content_type );
360 $self->response->charset( $self->charset ) if defined $self->charset;
361 $self->response->content($message);
362
363 $self->has_app &&
364 $self->app->execute_hook('core.error.after', $self->response);
365
366 $self->response->is_halted(1);
367 return $self->response;
368 }
369
370 sub backtrace {
371 my ($self) = @_;
372
373 my $message = $self->message;
374 if ($self->exception) {
375 $message .= "\n" if $message;
376 $message .= $self->exception;
377 }
378 $message ||= 'Wooops, something went wrong';
379
380 my $html = '<pre class="error">' . _html_encode($message) . "</pre>\n";
381
382 # the default perl warning/error pattern
383 my ($file, $line) = $message =~ /at (\S+) line (\d+)/;
384 # the Devel::SimpleTrace pattern
385 ($file, $line) = $message =~ /at.*\((\S+):(\d+)\)/ unless $file and $line;
386
387 # no file/line found, cannot open a file for context
388 return $html unless $file and $line;
389
390 # file and line are located, let's read the source Luke!
391 my $path = Path::Tiny::path($file);
392 return $html if !$path->is_file;
393
394 my @lines;
395 eval { @lines = $path->lines_utf8; 1; } or return $html;
396
397 $html .= qq|<div class="title">$file around line $line</div>|;
398
399 # get 5 lines of context
400 my $start = $line - 5 > 1 ? $line - 5 : 1;
401 my $stop = $line + 5 < @lines ? $line + 5 : @lines;
402
403 $html .= qq|<pre class="content"><table class="context">\n|;
404 for my $l ($start .. $stop) {
405 chomp $lines[$l - 1];
406
407 $html .= $l == $line ? '<tr class="errline">' : '<tr>';
408 $html .= "<th>$l</th><td>" . _html_encode($lines[$l - 1]) . "</td></tr>\n";
409 }
410 $html .= "</table></pre>\n";
411
412 return $html;
413 }
414
415 sub dumper {
416 my ($self,$obj) = @_;
417
418 # Take a copy of the data, so we can mask sensitive-looking stuff:
419 my $data = clone($obj);
420 my $censored = $self->censor->( $data );
421
422 #use Data::Dumper;
423 my $dd = Data::Dumper->new( [ $data ] );
424 my $hash_separator = ' @@!%,+$$#._(-- '; # Very unlikely string to exist already
425 my $prefix_padding = ' #+#+@%.,$_-!(( '; # Very unlikely string to exist already
426 $dd->Terse(1)->Quotekeys(0)->Indent(1)->Sortkeys(1)->Pair($hash_separator)->Pad($prefix_padding);
427 my $content = _html_encode( $dd->Dump );
428 $content =~ s/^.+//; # Remove the first line
429 $content =~ s/\n.+$//; # Remove the last line
430 $content =~ s/^\Q$prefix_padding\E //gm; # Remove the padding
431 $content =~ s{^(\s*)(.+)\Q$hash_separator}{$1<span class="key">$2</span> =&gt; }gm;
432 if ($censored) {
433 $content
434 .= "\n\nNote: Values of $censored sensitive-looking keys hidden\n";
435 }
436 return $content;
437 }
438
439 sub environment {
440 my ($self) = @_;
441
442 my $stack = $self->get_caller;
443 my $settings = $self->has_app && $self->app->settings;
444 my $session = $self->has_app && $self->app->_has_session && $self->app->session->data;
445 my $env = $self->has_app && $self->app->has_request && $self->app->request->env;
446
447 # Get a sanitised dump of the settings, session and environment
448 $_ = $_ ? $self->dumper($_) : '<i>undefined</i>' for $settings, $session, $env;
449
450 return <<"END_HTML";
451 <div class="title">Stack</div><pre class="content">$stack</pre>
452 <div class="title">Settings</div><pre class="content">$settings</pre>
453 <div class="title">Session</div><pre class="content">$session</pre>
454 <div class="title">Environment</div><pre class="content">$env</pre>
455 END_HTML
456 }
457
458 sub get_caller {
459 my ($self) = @_;
460 my @stack;
461
462 my $deepness = 0;
463 while ( my ( $package, $file, $line ) = caller( $deepness++ ) ) {
464 push @stack, "$package in $file l. $line";
465 }
466
467 return join( "\n", reverse(@stack) );
468 }
469
470 # private
471
472 # Replaces the entities that are illegal in (X)HTML.
473 sub _html_encode {
474 my $value = shift;
475
476 return if !defined $value;
477
478 $value =~ s/&/&amp;/g;
479 $value =~ s/</&lt;/g;
480 $value =~ s/>/&gt;/g;
481 $value =~ s/'/&#39;/g;
482 $value =~ s/"/&quot;/g;
483
484 return $value;
485 }
486
487 1;
488
489 __END__
490
491 =pod
492
493 =encoding UTF-8
494
495 =head1 NAME
496
497 Dancer2::Core::Error - Class representing fatal errors
498
499 =head1 VERSION
500
501 version 2.2.2
502
503 =head1 SYNOPSIS
504
505 use Dancer2::Core::Error;
506
507 my $error = Dancer2::Core::Error->new(
508 status => 404,
509 message => "No such file: `$path'"
510 );
511
512 $error->throw;
513
514 =head1 DESCRIPTION
515
516 With Dancer2::Core::Error you can throw reasonable-looking errors to the user
517 instead of crashing the application and filling up the logs.
518
519 This is usually used in debugging environments, and it's what Dancer2 uses as
520 well under debugging to catch errors and show them on screen.
521
522 =head1 ATTRIBUTES
523
524 =head2 show_stacktrace
525
526 =head2 charset
527
528 =head2 type
529
530 The error type.
531
532 =head2 title
533
534 The title of the error page.
535
536 This is only an attribute getter, you'll have to set it at C<new>.
537
538 =head2 status
539
540 The status that caused the error.
541
542 This is only an attribute getter, you'll have to set it at C<new>.
543
544 =head2 message
545
546 The message of the error page.
547
548 =head2 censor
549
550 The function to use to censor error messages. By default it uses the C<censor> method of L<Data::Censor>"
551
552 # default censor function used by `error_censor`
553 # is equivalent to
554 sub MyApp::censor {
555 Data::Censor->new(
556 sensitive_fields => qr/pass|card.?num|pan|secret/i,
557 replacement => "Hidden (looks potentially sensitive)",
558 )->censor(@_);
559 }
560 setting error_censor => 'MyApp::censor';
561
562 It can be configured via the app setting C<error_censor>. If provided,
563 C<error_censor> has to be the fully qualified name of the censor
564 function. That function is expected to take in the data as a hashref,
565 modify it in place and return the number of items 'censored'.
566
567 For example, using L<Data::Censor>.
568
569 # in config.yml
570 error_censor: MyApp::Censor::censor
571
572 # in MyApp::Censor
573 package MyApp::Censor;
574
575 use Data::Censor;
576
577 my $data_censor = Data::Censor->new(
578 sensitive_fields => [ qw(card_number password hush) ],
579 replacement => '(Sensitive data hidden)',
580 );
581
582 sub censor { $data_censor->censor(@_) }
583
584 1;
585
586 As a shortcut, C<error_censor> can also be the key/value combo of
587 a class and the arguments for its constructor. The created object
588 is expected to have a method C<censor>. For example, the use of
589 L<Data::Censor> above could also have been done via the config
590
591 error_censor:
592 Data::Censor:
593 sensitive_fields:
594 - card_number
595 - password
596 - hush
597 replacement: '(Sensitive data hidden)'
598
599 =head1 METHODS
600
601 =head2 my $error=new Dancer2::Core::Error(status => 404, message => "No such file: `$path'");
602
603 Create a new Dancer2::Core::Error object. For available arguments see ATTRIBUTES.
604
605 =head2 supported_hooks ();
606
607 =head2 throw($response)
608
609 Populates the content of the response with the error's information.
610 If I<$response> is not given, acts on the I<app>
611 attribute's response.
612
613 =head2 backtrace
614
615 Show the surrounding lines of context at the line where the error was thrown.
616
617 This method tries to find out where the error appeared according to the actual
618 error message (using the C<message> attribute) and tries to parse it (supporting
619 the regular/default Perl warning or error pattern and the L<Devel::SimpleTrace>
620 output) and then returns an error-highlighted C<message>.
621
622 =head2 environment
623
624 A main function to render environment information: the caller (using
625 C<get_caller>), the settings and environment (using C<dumper>) and more.
626
627 =head2 get_caller
628
629 Creates a stack trace of callers.
630
631 =head1 FUNCTIONS
632
633 =head2 _censor
634
635 An private function that tries to censor out content which should be protected.
636
637 C<dumper> calls this method to censor things like passwords and such.
638
639 =head2 my $string=_html_encode ($string);
640
641 Private function that replaces illegal entities in (X)HTML with their
642 escaped representations.
643
644 html_encode() doesn't do any UTF black magic.
645
646 =head2 dumper
647
648 This uses L<Data::Dumper> to create nice content output with a few predefined
649 options.
650
651 =head1 AUTHOR
652
653 Dancer Core Developers
654
655 =head1 COPYRIGHT AND LICENSE
656
657 This software is copyright (c) 2026 by Alexis Sukrieh.
658
659 This is free software; you can redistribute it and/or modify it under
660 the same terms as the Perl 5 programming language system itself.
661
662 =cut