morgon has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am rather new to Mojolicious and probably I am just being stupid, but I cannot figure out how to do achieve the exception handling behaviour I want with Mojolicious...

My problem is as follows:

I have some domain-specific classes that throw instances of Exception::Class that I want to use inside a Mojolicious REST-application.

What I would like to have is a way to set up an exception-handler where all exeptions would get routed to and where I would then determine which Template to render and which http-status code to return based on the class of the exception.

This is the closest I could achieve on my own to illustrate what I mean:

package Whatever::Controller use Mojo::Base qw(Mojolicious::Controller); use Whatever::Thingy; use Whatever::Exceptions; # <- based on Class::Exception sub do_something { my($this)=@_; my $input = $this->param("input"); # the following constructor potentially throws an exception my $thingy = Whatever::Thingy->new( input => $input ); $this->stash( thingy=> $thingy ); $this->render( format => "html", template => "thingy_template", ); } } sub render_exception { my($this, $ex)=@_; # now do something based on the class of $ex if($ex->isa("Whathever::Exception::SourMilk") { $this->render( format => "html", template => "exception", status => 501, ex => $ex, ); } else {.....} # and so on } 1;
So what I want is that in case an exception is thrown I end up in an exception handler where I can than choose a template and a status-code based on the class of the exception.

I would like to have all exception-handling code in one place and not have to catch them in each controller action.

In the above code I can indeed render the exception with a template of my choosing but I cannot influence the http-status code (in case of an exception always 500 is returned to the client).

The problem of course is that (as the name implies) render_exception only renders the exception but does not seem to allow for the status code to be manipulated.

So does anyone know how to achieve what I would like to have?

Many thanks!

Replies are listed 'Best First'.
Re: exception handling in Mojolicious
by Anonymous Monk on Sep 22, 2011 at 13:27 UTC

    By my reading of the docs, that should work

    Are you sure Whatever::Controller::render_exception gets called and calls render?

    Upgrade and/or file a bug report upstream

      It does get called and renders the template ok, but the wrong status code is returned to the client.

        It does get called and renders the template ok, but the wrong status code is returned to the client.

        How do you know that it gets called?