@@ -4,6 +4,7 @@ use strict;
4
4
use warnings;
5
5
# VERSION
6
6
7
+ use Try::Tiny;
7
8
use Dancer ' :syntax' ;
8
9
use Dancer::Exception ' :all' ;
9
10
use Dancer::Plugin;
@@ -28,6 +29,24 @@ register_exception ('InvalidMethod',
28
29
29
30
my @authorized_methods = (' get' , ' post' , ' put' , ' delete' );
30
31
32
+ =method exception_message
33
+
34
+ return the exception message
35
+ This method can be used to catch the exception if the code used already contained a try catch
36
+
37
+ =cut
38
+
39
+ sub exception_message{
40
+
41
+ return ' Route Timeout Detected' ;
42
+ }
43
+
44
+ =method timeout
45
+
46
+ Method that manage the timeout on a dancer request
47
+
48
+ =cut
49
+
31
50
sub timeout {
32
51
my ($timeout ,$method , $pattern , @rest );
33
52
if (scalar (@_ ) == 4){
@@ -48,27 +67,33 @@ sub timeout {
48
67
raise InvalidMethod => $method ;
49
68
}
50
69
70
+ my $exception_message = exception_message();
51
71
my $timeout_route = sub {
52
72
my $response ;
53
73
54
74
# if timeout is not defined but a value is set in the headers for timeout
55
75
$timeout = vars-> {header_timeout } if (!defined $timeout && defined vars-> {header_timeout });
56
76
57
77
# if timeout is not defined or equal 0 the timeout manager is not used
78
+ my $timeout_exception ;
58
79
if (!$timeout ){
59
80
$response = $code -> ();
60
81
}
61
82
else {
62
- eval {
63
- local $SIG {ALRM } = sub { croak (" Route Timeout Detected " ); };
83
+ try {
84
+ local $SIG {ALRM } = sub { croak ($exception_message ); };
64
85
alarm($timeout );
86
+
65
87
$response = $code -> ();
66
88
alarm(0);
89
+ }
90
+ catch{
91
+ $timeout_exception = $_ ;
67
92
};
68
93
alarm(0);
69
94
}
70
95
# Timeout detected
71
- if ($@ && $@ =~ / Route Timeout Detected / ){
96
+ if ($timeout_exception && $timeout_exception =~ / $exception_message / ){
72
97
my $response_with_timeout = Dancer::Response-> new(
73
98
status => 408,
74
99
content => " Request Timeout : more than $timeout seconds elapsed."
@@ -135,6 +160,9 @@ If the timeout is set to 0, the behavior is the same than without any timeout de
135
160
It's also possible to define route handlers that will set a per-request timeout protection, depending
136
161
on the value of the header C<X-Dancer-Timeout > .
137
162
163
+ If your Dancer code already use try catch, the exeption may be catched.
164
+ So exception_message method can be used to cath the content of the exception in your Dancer code.
165
+
138
166
=head1 AUTHOR
139
167
140
168
Frederic Lechauve, E<lt> frederic_lechauve at yahoo.frE<gt>
0 commit comments