check response code Mojo::UserAgent

32 views
Skip to first unread message

Natxo Asenjo

unread,
Jul 5, 2016, 2:52:19 AM7/5/16
to Mojolicious
hi,

when I issue a simple request like this:

my $login   = $ua->post($url_com);

Checking the response is simple:

if ( my $res = $login->success ) {
   ....
}
else {
    my $err = $login->error;
    die "$err->{code} response: $err->{message}" if $err->{code};
}

But how to do it when using a more complex request and saving the json data directly in the variable $sections (really cool that this is possible):

my $sections = $ua->get( "https://$url$api/sections/" => { 'token' => $token } )->res->json('/data');

if ( my  $sections->success ) {
    return $sections;
}
else {
    my $err = $sections->error;
    die "$err->{code} response: $err->{message}" if $err->{code};
}

I cannot use $sections->success :
Can't call method "success" on an undefined value at script.pl line ...

I am probably asking something very simple, my apologies for that, but the answer escapes me so far.

Thanks in advance.

--
regards,
Natxo

Ben van Staveren

unread,
Jul 5, 2016, 2:54:47 AM7/5/16
to mojol...@googlegroups.com
You want to use:

my $res = $ua->get( ...)->res;
my $sections;
if($res->success) {
   $sections = $res->json('/data');
} else {
  ...
--
You received this message because you are subscribed to the Google Groups "Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mojolicious...@googlegroups.com.
To post to this group, send email to mojol...@googlegroups.com.
Visit this group at https://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.

Natxo Asenjo

unread,
Jul 5, 2016, 4:23:06 AM7/5/16
to Mojolicious


On Tuesday, July 5, 2016 at 8:54:47 AM UTC+2, Ben van Staveren wrote:
You want to use:

my $res = $ua->get( ...)->res;
my $sections;
if($res->success) {
   $sections = $res->json('/data');
} else {
  ...
}

yes, that nearly did it:

my $res = $ua->get( ...) ;
my $sections;
if($res->success) {
   $sections = $res->res->json('/data');
} else {
  ...
}

 Thanks!

--
regards,
Natxo


Reply all
Reply to author
Forward
0 new messages