I am trying to create a function that deletes a user from Constant Contact. This function calls a wrapper class for constant contact, and it works, but if you feed it an email address that does not exist on their site it comes back with a catchable fatal error.
I am new to try/catch and I’m not quite getting where to place that so that I can create a graceful error message instead of the Catchable Fatal Error I’m getting. Below is my current code:
function ccdeleteuser($emailaddress)
{
//this code accesses the constant contact wrapper class to delete a user based on email
$ConstantContact = new ConstantContact("basic", "apikey", "usr", "pwd");
$SearchContact = $ConstantContact->searchContactsByEmail($emailaddress);
$DeleteContact = $ConstantContact->deleteContact($SearchContact[0]);
}
$emailtotry = "test@test.com"; //this is email is NOT in Constant Contact
ccdeleteuser($emailtotry);
Right now if I run this I get the following error:
Catchable fatal error: Argument 1 passed to ConstantContact::deleteContact() must be an instance of Contact, null given, called in [path to my page] on line 19 and defined in [path to constant contact php wrapper file] on line 214
Any help is appreciated!
The right way to do this is to test for null first:
With try… catch, you might make it look like this:
As a general note, it is always best to act proactively to prevent exceptions and not simply catch them after the fact. I’ll even go so far as to say that you should consider it a rule to always do everything in your power to prevent the possibility of an exception and only use try… catch as a last possible resort.