morgon has asked for the wisdom of the Perl Monks concerning the following question:
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:
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.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;
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 morgon (Priest) on Sep 22, 2011 at 13:40 UTC | |
by Anonymous Monk on Sep 22, 2011 at 14:03 UTC | |
by morgon (Priest) on Sep 22, 2011 at 23:46 UTC |