Wednesday, July 10, 2013

Sending Error Responses in Poet

I'm playing around with Poet, a new Mason-based web framework in Perl.

You can read more about it here:
http://www.masonhq.com/

One thing seems under-documented: how do you deal with error pages?

Well, you probably noticed there is a directory called "static/errors" and in it there are things like "404.html" and so on. So far so good: these are what they appear to be.

But how do you trigger one?

The documentation for Poet::Mason shows a very useful method:

abort (status)
clear_and_abort (status)
    These methods are overridden to set the response status
    before aborting, if status is provided. e.g. to send back
    a FORBIDDEN result:

        $m->clear_and_abort(403);

    This is equivalent to

        $m->res->status(403);
        $m->clear_and_abort();

    If a status is not provided, the methods work just as
    before.

Great, so all we need is:

<%init>
    # you can't see me!
    $m->clear_and_abort(404);
</%init>

and... boom! You are served the standard 404 page from your "static/errors" directory.

But what about a 400 BAD REQUEST, which is more likely to be needed in the first place? Just changing that status code to 400 gives us... only the status code in the response headers, and a blank page. At least that much worked.

But a quick look at "static/errors" shows there is no "400.html" -- and all we need to do is drop one in, right? Wrong. Or half-wrong anyway: we do need to create that file, but just creating it isn't enough.

It turns out this is controlled in "bin/app.psgi" (around line 20). The command:

enable "ErrorDocument",
    map { $_ => $poet->static_path("errors/$_.html") }
    qw(401 403 404 500);

So now we just add a "400" to that list and restart the server, right?

RIGHT!

Hope that helps.

0 Comments:

Post a Comment

<< Home