سؤال

I am trying to create a subscribe method for my laravel app that uses the mailchimp api to subscribe a user to a given list. The method works fine when the email address is not already on the lsit. when it is already subscribed the mailchimp api throws the following error

Mailchimp_List_AlreadySubscribed blah@blah.co is already subscribed to list Tc App Test List. Click here to update your profile.

with the following code being shown

public function castError($result) {
        if($result['status'] !== 'error' || !$result['name']) throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result));

        $class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error';
        return new $class($result['error'], $result['code']);
    }

I have attempted a try catch block to catch the error but it is still being returned to the browser, here is what I tried and were it says MailChimp_Error I tried with Exception as well.

public function subscribe($id, $email, $merge_vars)
    {
        try {
            $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
        } catch (MailChimp_Error $e) {
            $response = 'an error has occured';
        }

        return $response;
    }

Ultimately I want to be able to run the method and then either return either a success message or a message describing the issue to the user. the 3 possible mailchimp method errors are Email_notexists, list_alreadysubscribed and list does not exist although tihs last one should not occur as I am providing the list in the source code.

edit 1; after being in touch with mailchimp api support they suggested this code but the error still gets returned to the browser in its entirety

try {
     $results = $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (Mailchimp_Error $e) {
      if ($e->getMessage()) {
           $error = 'Code:'.$e->getCode().': '.$e->getMessage();
      }
}

echo $error;
هل كانت مفيدة؟

المحلول 2

Subscribe is in a namespace Acme\Emails\Subscribe so catch(Mailchimp_Error $e) looks for Mailchimp_Error in this namespace.

Changing it to catch(\Mailchimp_Error $e) makes it look in the root namespace and then it works as intended

نصائح أخرى

You can do

 try
                    {
                        $response = $this->mailchimp->lists->addListMember($list_id, [
                            "email_address" => $email,
                            "status" => "subscribed",
                        ]);
                        
                    }
                    catch (\EXCEPTION $e) {
                        return $e->getMessage();
                       

                    } 

The \EXCEPTION handles a sort of error for stripe

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top