Mojolicious lite how to redirect for not found and server error pages to user defined error page
Asked Answered
G

3

7

How to redirect user defined error page for not found and server error pages to user define page Mojolicious lite

Genuflection answered 7/11, 2012 at 14:57 Comment(0)
C
12

You can add a template for your custom page named exception.html.ep or not_found.html.ep at the end of your liteapp.

For example:

use Mojolicious::Lite;
get '/' => sub {
    my $self = shift;
    $self->render(text => "Hello.");
};
app->start;

__DATA__
@@ not_found.html.ep
<!DOCTYPE html>
<html>
  <head><title>Page not found</title></head>
  <body>Page not found <%= $status %></body>
</html>

For a reference, see the Mojolicious rendering guide.

The renderer will always try to find exception.$mode.$format.* or not_found.$mode.$format.* before falling back to the built-in default templates.

Cocoa answered 8/11, 2012 at 2:26 Comment(0)
S
8

I wanted to run some code in my 404 page so borrowing from here https://groups.google.com/forum/#!topic/mojolicious/0wzBRnetiHo

I made a route that catches everything and placed it after all my other routes, so urls that don't match routes fall through to this:

any '/(*)' => sub {
    my $self = shift;
    $self->res->code(404);
    $self->res->message('Not Found');

    # 404       
    $self->stash( { 
        # ... my stuff in the stash ... 
    } );

    $self->render('mytemplate', status => 404);
};
Shorthand answered 16/10, 2013 at 13:7 Comment(1)
This was a good hint for me, but I don't think it works in Mojo 9 now. any '/*', without the parens, does.Marketing
M
0

I had an API that wanted to send back 404 errors as it would any other error—same JSON format and whatnot.

I had this snippet at the end of startup (full app, not lite). Since this is the last defined route, it only picks up anything not already handled. And, since this handles all that, Mojo never gets the chance to use its own 404 handling by looking for templates:

  $self->routes->any('/*')->to(
    controller => 'Base',
    action     => 'not_found'
  );
Marketing answered 22/2, 2022 at 21:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.