handle lwp timeout effectively

六月ゝ 毕业季﹏ 提交于 2019-12-05 05:41:39

LWP::Agent's get() returns a HTTP::Response object that you can use for checking errors:

use LWP::Agent;
use HTTP::Status ();

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $response = $ua->get($url);

if ($response->is_error) {
    printf "[%d] %s\n", $response->code, $response->message;

    # record the timeout
    if ($response->code == HTTP::Status::HTTP_REQUEST_TIMEOUT) {
        ...
    }
}

Btw, the better practice nowadays is to use Try::Tiny instead of eval {...}. It gives you try {...} catch {...}. and it resolves some problems with checking if $@ (see the background section in the Try::Tiny documentation).

You can do the equivalent of a try{} catch {} in Perl using eval blocks:

http://perldoc.perl.org/functions/eval.html

ysth

For most purposes, LWP::UserAgent's timeout is sufficient, but it does suffer some drawbacks… it applies to each system call, rather than to the aggregate of them. If you truly need a fixed timeout period, this is one of the things that LWPx::ParanoidAgent takes care off.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!