2017-07-01 85 views
0
// https://api.xivdb.com/character/17803411 <-- fail 
// https://api.xivdb.com/character/1395894 <-- success 
function GetCharacter($url) 
{ 
    $client = new GuzzleHttp\Client(); 

    $res = $client->get($url); 

    echo $res->getStatusCode(); 
    exit(); 


    return json_decode($res->getBody(), true); 
} 

在上面的代码中,当我使用成功的$ url时,我的代码工作,并且我得到状态码200.但是,当我使用$网址失败了,我刚刚得到的通用

500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed.

现在,对于失败$网址的回报,直接将它的时候是:

{ code: 404, error: "The character you are looking for could not be found. The character may still be being processed or the XIVSync service has gone down." }

我的问题是,为什么$客户端 - > get()从成功的$ url中返回JSON,但只是平坦失败的另一个?

回答

3

如果回答不是200,Guzzle会触发异常。这就是为什么你会在你身边看到500错误。

你将不得不像这样捕获这个错误。

try { 
    $res = $client->get($url); 
} 
catch (GuzzleHttp\Exception\ClientException $e) { 
    // error. 
} 
+0

现在行了?如果是这样,你能接受答案,请:) –

0

我试图请求这些端点。

<?php 

require 'vendor/autoload.php'; 

use GuzzleHttp\Client; 
use GuzzleHttp\Exception\ClientException; 

$client = new Client(); 

$validApiEndpoint = 'https://api.xivdb.com/character/1395894'; 
$invalidApiEndpoint = 'https://api.xivdb.com/character/17803411'; 

try { 
    $response = $client->get($invalidApiEndpoint); 

    echo $response->getStatusCode(); 
} catch (ClientException $e) { 
    echo $e->getMessage(); 
} 

狂饮被简单地从请求抛出异常,因为状态码不被200〜$invalidApiEndpont

您应该使用适配器模式创建某种适配器类,以防止在应用程序中出现问题时直接引发异常。直接使用Guzzle客户端是一个糟糕的主意。

如果你在你的情况下,大约适配器模式实现一个问题,我可以介绍给你。