Skip to content

Instantly share code, notes, and snippets.

@hayajo
Last active August 29, 2015 14:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hayajo/07cbf3ce45be34634a9a to your computer and use it in GitHub Desktop.
Save hayajo/07cbf3ce45be34634a9a to your computer and use it in GitHub Desktop.
MojoliciousでエラーをJSONで返す
#!/usr/bin/env perl
use Mojolicious::Lite;
hook before_render => sub {
my ($c, $args) = @_;
my $template = $args->{template};
return unless $template;
my $status = $args->{status};
return unless $status >= 400;
my $msg
= ($status == 404)
? 'Not Found'
: ($args->{exception} || 'Unknown Exception');
$args->{json}
= {error => {status => $status, message => $msg}};
};
app->renderer->default_format('json');
get '/' => sub {
my $c = shift;
$c->render( json => { message => "Welcome to the Mojolicious real-time web framework!" } );
};
app->start;
@hayajo
Copy link
Author

hayajo commented Dec 29, 2014

もっとスマートな方法なかったっけか?

@hayajo
Copy link
Author

hayajo commented Apr 16, 2015

ヘッダー考慮してなかった

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment