Bruno Teixeira Bruno Teixeira - 16 days ago 11
PHP Question

Laravel - Can't handle RequestException (Guzzle + MailChimp)

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';
}
}



}
}

Answer

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
    }
}