Search code examples
perlcatalyst

Return or detach from Catalyst controller action?


Let's assume I have the following action in a Catalyst::Controller that requires the parameter bar to be present. If this parameter is not given in the query I want to show an error message:

sub foo : Local {
    my ($self, $c) = @_;

    if (!$c->req->params->{bar}) {
        $c->stash->{error} = "Parameter 'bar' missing!";
        $c->detach; # or return; ?
    }

    # some more logic...
}

Now my question is: does it make a difference whether I do $c->detach or simply return from the action? At first glance the behaviour seems to be identical, but are there any advantages or disadvantages of either option?


Solution

  • According to the documentation for detach() :

    The same as forward(), but doesn't return to the previous action when processing is finished. When called with no arguments it escapes the processing chain entirely.

    Inspecting the source, see line 278, we see that detach() throws a Catalyst::Exception::Detach exception and thus never returns to the caller.

    So using $c->detach() is not the same as calling return to return from the action sub. Calling return will continue the action processing chain, while $c->detach() will not.