Laravel 5.5 - 作业 - 使用“GuzzleHttp \ Exception”触发失败()方法

时间:2017-11-09 16:48:15

标签: php guzzle laravel-5.5

我正在构建一个简单的Laravel作业,它将GuzzleHttp\Client的GET请求发送到远程Web服务。 当GuzzleHttp请求返回错误时,它会抛出GuzzleHttp\Exception\ClientException的实例,但failed()方法必须是app\Jobs\Exception的实例。 这是代码:

namespace app\V1\Jobs;
class setRegionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    // . . .
    public function handle()
    {
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://link_to_api/'),
            'timeout'  => 2.0,
        ]);
        $res = $client->request('GET', '?key=param1&key2=param2');
        if ($res->getStatusCode() == 200) {
            $data = json_decode($res->getBody(), true)['data'];
        } else {
            $data = null;
        }
    }

    public function failed(Exception $exception)
    {
         // do something
    }
}

然后,当$client->request('GET', '?key=param1&key2=param2')抛出异常时,ERROR为:

[2017-11-09 14:38:40] local.ERROR: Type error: Argument 1 passed to app\Jobs\setRegionJob::failed() must be an instance of app\Jobs\Exception, instance of GuzzleHttp\Exception\ClientException given.

我如何触发failed()方法?

0 个答案:

没有答案