dipl0
dipl0

Reputation: 1077

Perl mojolicious controllers redirecting to not_found page

So I am trying to return a 404 not found page in a mojolicious controller, the method is called as part of an under statement and although it temporarily redirects to the not_found page it eventually goes to the specified action and destination.

sub get_host_id {
my $self = shift;
my $host_id = $self->stash('host_id');
return $self->redirect_to('not_found');
return $self->render('not_found');

return $self->reply->not_found;
$self->render(text => '404 Not Found');
$self->rendered(404);
return $self->reply->not_found;
            return $self->render(
          status => 404,
          template => 'not_found',
);
                    $self->reply->not_found;
      }
              template => 'not_found',
    );
                        $self->reply->not_found;
}

solved:

  sub get_host_id {
    my $self = shift;


    return $self->redirect_to('/not_found');
        }

Upvotes: 1

Views: 306

Answers (1)

Christopher Causer
Christopher Causer

Reputation: 1494

the method is called as part of an under statement

Here's the problem I think. If you redirect, you then need to return false. From the docs

The actual action code for this destination needs to return a true value or the dispatch chain will be broken

Looking at the source code for the not_found helper, the return value is always the controller object, which is true. As such, the under action will always continue to the next action regardless if a 404 has been rendered. This is not what you'd naively expect, or want.

To fix this behaviour, you will need to write something like the following in place of return $self->reply->not_found;

$self->reply->not_found and return;

Upvotes: 1

Related Questions