clemep8

http_throw and Dancer2

Feb 3rd, 2021
158
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl
  2. use Test::More tests => 2;
  3. use Plack::Test;
  4. use Plack::Builder;
  5. use Plack::Middleware::HTTPExceptions;
  6. use HTTP::Request::Common;
  7. use HTTP::Throwable::Factory qw(http_throw);
  8.  
  9. sub psgi_app {
  10.     my $env = shift;
  11.     if ($env->{PATH_INFO} eq '/api') {
  12.         http_throw(NotAcceptable => {});
  13.     }
  14. };
  15.  
  16. my $psgi_app = \&psgi_app;
  17.  
  18. # temporary holding spot for HTTP::Throwable to allow Throwable-based error responses
  19. # (by default, Dancer2 will rethrow any exception it receives as 500, so override this behavior)
  20. our $_SAVEERR;
  21.  
  22. package DancerApp {
  23.         use Scalar::Util qw(blessed);
  24.         use HTTP::Throwable::Factory qw(http_throw);
  25.         use Dancer2;
  26.  
  27.         set serializer => 'JSON';
  28.  
  29.         hook after_error => sub {
  30.                 my $response = shift;
  31.  
  32.                 if (my $e = $_SAVEERR) {
  33.                         undef $_SAVEERR;
  34.                         status $e->{'status_code'};
  35.                         halt;
  36.                 }
  37.         };
  38.  
  39.         hook on_route_exception => sub {
  40.                 my ($app, $error) = @_;
  41.  
  42.                 # if a Throwable is present, then save it
  43.                 if (blessed $error && $error->does('HTTP::Throwable')) {
  44.                         $_SAVEERR = $error;
  45.                 }
  46.         };
  47.  
  48.         get '/api' => sub {
  49.                 http_throw(NotAcceptable => {});
  50.         };
  51. };
  52.  
  53. my $dancer_app = DancerApp->to_app;
  54.  
  55. my $plack_psgi = builder {
  56.     enable "HTTPExceptions";
  57.     $psgi_app
  58. };
  59.  
  60. my $plack_dancer = builder {
  61.     $dancer_app
  62. };
  63.  
  64. # PSGI:
  65. my $t = Plack::Test->create($plack_psgi);
  66. my $r = $t->request(GET '/api');
  67. is($r->code, 406, 'GET /api');
  68.  
  69. # DANCER:
  70. my $t2 = Plack::Test->create($plack_dancer);
  71. my $r = $t2->request(GET '/api');
  72. is($r->code, 406, 'GET /api');
RAW Paste Data