PHP错误消息帮助和尝试/捕获

时间:2011-08-31 13:49:53

标签: php try-catch constantcontact

我正在尝试创建一个从Constant Contact中删除用户的函数。这个函数调用一个包装类来进行持续联系,它可以正常工作,但是如果你给它提供一个在他们的站点上不存在的电子邮件地址,它会返回一个可捕获的致命错误。

我是尝试/捕获的新手,我不知道在哪里放置它以便我可以创建一个优雅的错误消息而不是我得到的可捕获的致命错误。以下是我目前的代码:

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);

现在,如果我运行此操作,我会收到以下错误:

  

捕获致命错误:传递给ConstantContact :: deleteContact()的参数1必须是Contact的实例,null给定,在第19行的[我的页面的路径]中调用,并在[常量联系php包装文件的路径]中定义在第214行

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

正确的方法是首先测试null:

function ccdeleteuser($emailaddress)
{

    $ConstantContact = new ConstantContact("basic", "apikey", "usr", "pwd");
    $SearchContact = $ConstantContact->searchContactsByEmail($emailaddress);
    // first makes sure that the 0 index of of SearchContact is accessible at all
    // then it ensures that only something "truthy" will trigger delete -- this
    // means that if $SearchContact[0] is null, the function won't try to delete
    if( $SearchContact && isset( $SearchContact[0] ) && $SearchContact[0])
        $DeleteContact = $ConstantContact->deleteContact($SearchContact[0]);  
    else
        echo "Can't do nothin'"; // do something useful?
}

使用try ... catch,你可能会看起来像这样:

function ccdeleteuser($emailaddress)
{

    $ConstantContact = new ConstantContact("basic", "apikey", "usr", "pwd");
    $SearchContact = $ConstantContact->searchContactsByEmail($emailaddress);
    try
    {
        // keep this... it is still useful
        if( $SearchContact && isset( $SearchContact[0] ) && $SearchContact[0])
            $DeleteContact = $ConstantContact->deleteContact($SearchContact[0]);  
        else
            echo "Can't do nothin'";
    }
    catch( Exception $e )
    {
        // I'm making up a function "log" which will record that an error 
        // has taken place. It is a good idea to always log all exceptions
        // so that you don't accidentally obfuscate something important
        log( $e->getMessage() );
        // do something useful
    }
}

作为一般性说明,最好主动采取措施防止例外,而不是简单地在事后发现。我甚至会说你应该认为你应该尽一切力量来防止异常的可能性并且只使用try ... catch作为最后一种可能的手段。