How in guzzlehttp/guzzle error to get access to title, status, detail fields of returned error?

41 Views Asked by At

In laravel 10 app with guzzlehttp/guzzle ^7.8.0 catching runtime error of mailchimpListId method of https://github.com/mailchimp/mailchimp-marketing-php (v3.0) library getContents method of error :

try {
    $response = $this->getApiClient()->lists->addListMember($this->mailchimpListId, [
        "email_address" => $email,
        "status" => "subscribed",
        'merge_fields' => $userMergeFields,
    ]);

} catch (ClientException $e) {
    \Log::info($e->getMessage());
    \Log::info(varDump($e->getResponse()->getBody()->getContents());

returns string with all 3 fields :

[2024-02-18 07:18:45] local.INFO: scalar => (string) :{"title":"Member Exists","status":400,"detail":"[email protected] is already a list member. Use PUT to insert or update list members.","instance":"4d85bc54-136f-e637-92e2-3c1bf9f1048c"}

I try to get access to all 3 fields title", status, detail, but I did not find how can I do it. I tried like :

\Log::info(varDump($e->getResponse()->getBody()->getTitle(), ' -10 $e->getResponse()->getTitle()::'));

But got error :

Call to undefined method GuzzleHttp\Psr7\Response::getTitle()

How can I get access to these 3 fields ?

1

There are 1 best solutions below

0
Karl Hill On BEST ANSWER

The error message you're getting is a JSON string. You can convert this JSON string into an associative array using json_decode function in PHP. After that, you can access the fields title, status, and detail as array elements.

Here is how you can do it:

try {
    $response = $this->getApiClient()->lists->addListMember($this->mailchimpListId, [
        "email_address" => $email,
        "status" => "subscribed",
        'merge_fields' => $userMergeFields,
    ]);

} catch (ClientException $e) {
    $errorResponse = json_decode($e->getResponse()->getBody()->getContents(), true);

    \Log::info('Title: ' . $errorResponse['title']);
    \Log::info('Status: ' . $errorResponse['status']);
    \Log::info('Detail: ' . $errorResponse['detail']);
}