perldancer

Perl Dancer2 default route failing


I am wanting to not have perl dancers default 404 "Sorry, this is the void." response come up when ever a matching route cannot be found. I also need to do some other task such as error logging when ever this happens.

Here is dancers documentation i followed on creating a default route. https://metacpan.org/pod/Dancer2::Cookbook#Default-Route

This is what i have at the bottom of my main routes file

any qr{.*} => sub {
    status 404;
    template 'test_error_template', { path => request->path };
};

The problem is i still keep getting the default dancer 404 message if an invalid route is requested. Somehow this route is not being picked up.

This is what comes up in development.log if i try going to a non existing route

[server:5931] core @2020-01-22 10:31:55> looking for get /non_existing_route in /usr/share/perl5/vendor_perl/Dancer2/Core/App.pm l. 36
[server:5931] core @2020-01-22 10:31:55> Entering hook core.error.init in (eval 230) l. 1
[server:5931] core @2020-01-22 10:31:55> Entering hook core.error.before in (eval 230) l. 1
[server:5931] core @2020-01-22 10:31:55> Entering hook core.error.after in (eval 230) l. 1

Can anyone help? I do have more than one routes files, could this be part of the issue?

Thanks


Solution

  • So in my case the problem was having a prefix set in the routes file. The default route wouldn't get triggered unless i included the prefix in the url. Eg /myprefix/invalid_route would call the default route but just calling /invalid_route wouldn't, resulting in the 404 error. I have not completely come up with a work around as yet but this does at least answer my original question.

    Edit:

    Solved it. I created a new route file default.pm that contains only the default route with prefix '/' and put it last in app.psgi. This way it is reached only when all else fails.

    app.psgi

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    use main_routes;
    use default;
    myapp->to_app;
    

    default.pm

    package default;
    
    prefix '/';
    
    any qr{.*} => sub {
        #log and do other stuff here
        return 'my default route';
    };
    
    true;