perlmojoliciousmojolicious-lite

How to change Mojolicious Lite default error not found to a custom json response


I'm creating a json web service using Mojolicious Lite.

By default Mojolicious returns a HTML response for a server error or not found error.

Is there a way to overwrite this to a custom JSON response?


Solution

  • Here are two approaches:

    1. Use json as the app's default format and use a not_found.*.json.ep template

      use Mojolicious::Lite;
      app->renderer->default_format('json');
      app->start;
      __DATA__
      
      @@ not_found.development.json.ep
      {"not":"found","code":404,"data":{"key1":"value1","key2":[42,19,"value3"]}}
      
    2. Override json payload with a before_render hook.

      use Mojolicious::Lite;
      hook before_render => sub {
          my ($c,$args) = @_;
          if ($args->{template} && $args->{template} eq 'not_found') {
              $args->{json} = { "too bad" => "so sad" };
          }
      };
      app->start;