in reply to How can I have a Dancer2 before hook return an HTTP error?

Hi,

First of all, as you may know, you don't need to code anything to get a 404 error response for a path that does not exist.

use strict; use warnings; use Dancer2; get '/' => sub { return 'Hello, world'; }; dance;
$ curl localhost:3000/does_not_exist
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0 +, user-scalable=yes"> <title>Error 404 - Not Found</title> <link rel="stylesheet" href="http://localhost:3000/css/error.css"> </head> <body> <h1>Error 404 - Not Found</h1> <div id="content"> /does_not_exist </div> <div id="footer"> Powered by <a href="http://perldancer.org/">Dancer2</a> 1.1.2 </div> </body> </html>

To return an error page based on something like an ID that is not allowed, use send_error:

use strict; use warnings; use Dancer2; get '/hello/:name' => sub { my $name = route_parameters->get('name'); return "Hello, $name"; }; hook before => sub { my $name = route_parameters->get('name'); is_disallowed($name) and send_error("$name is disallowed", 401); }; sub is_disallowed { my $name = shift; return $name eq 'nick' ? 1 : 0; } dance;
$ curl localhost:3000/hello/lembark
Hello, lembark
$ curl localhost:3000/hello/nick
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0 +, user-scalable=yes"> <title>Error 401 - Unauthorized</title> <link rel="stylesheet" href="http://localhost:3000/css/error.css"> </head> <body> <h1>Error 401 - Unauthorized</h1> <div id="content"> nick is disallowed </div> <div id="footer"> Powered by <a href="http://perldancer.org/">Dancer2</a> 1.1.2 </div> </body> </html>

See the documentation.

Hope this helps

update: included the before hook, d'oh


The way forward always starts with a minimal test.