0

I'm trying to handle a 404 request exception. It's the first time I'm using Guzzle so I'm unable to handle the exception without the error promps first, I need to check the error code because on the mailchimp API its the error code that gives us the informations we need.

Instead i'm getting this in response - http://prntscr.com/db9ari

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Newsletter;
use GuzzleHttp\Client;

class NewsletterController extends Controller
{


    public function api()
    {

        $mailchimp = new Client(['base_uri' => 'https://us14.api.mailchimp.com/3.0/']);

        try {
            $checkEmail = $mailchimp->request('GET', 'lists/LIST-ID/members/' . md5('EMAIL), [ 'headers' => [ 'Authorization' => 'apikey ' . config('globals.mailchimp_key') ]]);
        }

        catch( RequestException $exception ) {

            if ($exception->getStatusCode() === 404)
            {
                return 'STRING THAT I WANT TO RETURN IN CASE OF ERROR';
            }
        }



    }
}

2 Answers 2

2

According to the Guzzle documentation:

A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the http_errors request option is set to true

You can solve this in one of two ways:

  • Setting the http_errors value to false when instantiating your client. For your code this woud look like so: $mailchimp = new Client(['base_uri' => 'https://us14.api.mailchimp.com/3.0/', 'http_errors' => false]);

  • Wrap your call in a try/catch and catch the ClientException.

Guzzle will also throw a ServerException for any 500 level errors, which you can deal with in the same way

Sign up to request clarification or add additional context in comments.

Comments

0

Try usign something like this:

try {
    $checkEmail = $mailchimp->request('GET', 'lists/LIST-ID/members/' . md5('EMAIL), [ 'headers' => [ 'Authorization' => 'apikey ' . config('globals.mailchimp_key') ]]);
}catch( \Exception $e ) {
    if ($e instanceof GuzzleHttp\Exception\RequestException){
        if ($exception->getStatusCode() === 404)
        {   
            return 'STRING THAT I WANT TO RETURN IN CASE OF ERROR';
        }
    }else{
        // do anything else here
    }
}

2 Comments

That kind of works! I got this (prntscr.com/db9m77), how can I use "#code" ?
try $e->getResponse()->getStatusCode();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.