Skip to content

Commit

Permalink
better exception handling examples
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jun 12, 2012
1 parent 86cb9d3 commit b32b850
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 17 deletions.
11 changes: 2 additions & 9 deletions lib/Mojo/Transaction.pm
Expand Up @@ -268,17 +268,10 @@ successful or C<undef> otherwise. Connection and parser errors have only a
message in C<error>, 400 and 500 responses also a code.
# Sensible exception handling
if (my $res = $tx->success) {
say $res->body;
}
if (my $res = $tx->success) { say $res->body }
else {
my ($message, $code) = $tx->error;
if ($code) {
say "$code $message response.";
}
else {
say "Connection error: $message";
}
say $code ? "$code $message response." : "Connection error: $message";
}
Error messages can be accessed with the C<error> method of the transaction
Expand Down
16 changes: 8 additions & 8 deletions lib/Mojo/UserAgent.pm
Expand Up @@ -534,6 +534,14 @@ Mojo::UserAgent - Non-blocking I/O HTTP 1.1 and WebSocket user agent
# Say hello to the Unicode snowman with "Do Not Track" header
say $ua->get('www.☃.net?hello=there' => {DNT => 1})->res->body;
# Form POST with exception handling
my $tx = $ua->post_form('search.cpan.org/search' => {q => 'mojo'});
if (my $res = $tx->success) { say $res->body }
else {
my ($message, $code) = $tx->error;
say $code ? "$code $message response." : "Connection error: $message";
}
# Quick JSON API request with Basic authentication
say $ua->get('https://sri:s3cret@search.twitter.com/search.json?q=perl')
->res->json('/results/0/text');
Expand All @@ -545,14 +553,6 @@ Mojo::UserAgent - Non-blocking I/O HTTP 1.1 and WebSocket user agent
$ua->max_redirects(5)->get('www.reddit.com/r/perl/')
->res->dom('p.title > a.title')->each(sub { say $_->text });
# Form POST with exception handling
my $tx = $ua->post_form('search.cpan.org/search' => {q => 'mojo'});
if (my $res = $tx->success) { say $res->body }
else {
my ($message, $code) = $tx->error;
say "Error: $message";
}
# IPv6 PUT request with content
my $tx
= $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hello!');
Expand Down

0 comments on commit b32b850

Please sign in to comment.