Вопрос

I have an under statement that may generate and error (for instance, authentication error). I use content negotiation all over, and I'd like to return the error inside the under in a proper format. An example code:

under sub {
  my $self = shift;

  # Authenticated
  my $token = $self->param('token') || '';
  return 1 if $token eq '123456';

  # Not authenticated
  $self->respond_to(
    json => {
      json => { error => 'Invalid authentication token.' },
      status => 401
    },
    text => {
      text => 'Unauthorized.',
      status => 401
    }
  );
  return undef;
}

I can use render inside under, but respond_to won't work. Probably under work for that. But in that case, what should I do?

Это было полезно?

Решение

In Galileo I have an auth_fail helper which does something like this. While I work out an example, see that code (and the if_author and if_admin unders).

Ok here is an example, the trick turned out to be (at least for this mechanism) before you can redirect to your failure handler, you need to flash the format, which make it available to the next handler.

#!/usr/bin/env perl

use Mojolicious::Lite;

any '/fail' => sub {
  my $self = shift;
  $self->respond_to(
    json => {
      json => { error => 'Invalid authentication token.' },
      status => 401
    },
    text => {
      text => 'Unauthorized.',
      status => 401
    }
  );
};

under sub {
  my $self = shift;

  # Authenticated
  my $token = $self->param('token') || '';
  return 1 if $token eq '123456';

  # Not authenticated
  $self->flash( format => $self->param('format') );
  $self->redirect_to('fail');
  return undef;
};

any '/private' => sub {
  my $self = shift;
  $self->respond_to(
    json => {
      json => { launch_codes => '9999999' },
    },
    text => {
      text => 'Launch Code: 9999999',
    }
  ); 
};

app->start;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top