fatal_handler()
allows alternative handlers to be defined in place of (or in
addition to) the default redirect handler that is called on a fatal error.
Calls should be made with 1 parameter: the subroutine to call in the case of a fatal error. The subroutine is passed 3 parameters: the DSL, the message in question, and the reason. The subroutine should return true or false depending on whether it handled the error. If it returns false, the next fatal handler is called, and if there are no others then the default redirect fatal handler is called.
fatal_handler sub { my ($dsl, $msg, $reason) = @_; return if $dsl->app->request->uri !~ m!^/api/!; status $reason eq 'PANIC' ? 'Internal Server Error' : 'Bad Request'; $dsl->send_as(JSON => { error => 1, error_description => $msg->toString, }, { content_type => 'application/json; charset=UTF-8', }); };
fatal_handler sub {
my ($dsl, $msg, $reason, $default) = @_; (my $ctype = $dsl->request->header('content-type')) =~ s/;.*//; return if $ctype ne 'application/json'; status $reason eq 'PANIC' ? 'Internal Server Error' : 'Bad Request'; $dsl->send_as(JSON => { error => 1, description => $msg->toString, }, { content_type => 'application/json; charset=UTF-8', }); };
process()
is an eval, but one which expects and understands exceptions
generated by Log::Report. Any messages will be logged as normal in
accordance with the dispatchers, but any fatal exceptions will be caught
and handled gracefully. This allows much simpler error handling, rather
than needing to test for lots of different scenarios.
In a module, it is enough to simply use the error
keyword in the event
of a fatal error.
The return value will be 1 for success or 0 if a fatal exception occurred.
See the DETAILS for an example of how this is expected to be used.
This module is configured only once in your application. The other modules
which make your website do not need to require this plugin, instead they
can use Log::Report
to get useful functions like error and fault.
All the standard Log::Report functions are available to use. Please see the The Reason for the report for details of when each one should be used.
Log::Report class functionality to class messages (which can then be tested later):
notice __x"Class me up", _class => 'label'; ... if ($msg->inClass('label')) ...
Dancer2::Plugin::LogReport has a special message class, no_session
,
which prevents the message from being saved to the messages session
variable. This is useful, for example, if you are writing messages within
the session hooks, in which case recursive loops can be experienced.
This is a special additional type, equivalent to notice
. The difference is
that messages using this keyword will have the class success
added, which
can be used to color the messages differently to the end user. For example,
manual Dancer2::Plugin::LogReport::Message#bootstrap_color uses this to display the
message in green.