PiousVenom
PiousVenom

Reputation: 6918

$client->get() in Guzzle failing to return JSON

// 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 );
}

In the above code, when I use the successful $url, my code works and I get the status code 200. However, when I use the $url that fails, I just get the generic

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

Now, the return for the fail $url, when going directly to it is:

{ 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." }

My question is, why the $client->get() returns the JSON from the successful $url, but just flat fails on the other?

Upvotes: 0

Views: 741

Answers (2)

Paweł Wrzeszcz
Paweł Wrzeszcz

Reputation: 106

I've tried to request those endpoints.

<?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();
}

Guzzle is simply throwing an exception, because of the status code being not 200 from the request to $invalidApiEndpont.

You should create some kind of adapter class using Adapter Pattern to prevent exceptions from being thrown directly if this is a problem in your application. Using Guzzle client directly is a bad idea.

If you have a question about Adapter Pattern implementation in your case, I can describe it for you.

Upvotes: 1

Pascal Meunier
Pascal Meunier

Reputation: 715

Guzzle will trigger an exception if the response is not 200. That's why you see the 500 error on your side.

You will have to catch this error like this.

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

Upvotes: 3

Related Questions