2011-08-31 65 views
0

我想創建一個刪除從不斷接觸用戶的功能。這個函數爲常量聯繫調用一個包裝類,並且它可以工作,但是如果給它提供一個在他們的站點上不存在的電子郵件地址,它會返回一個可捕獲的致命錯誤。PHP錯誤信息幫助和try/catch

我是新來的try/catch和我不太得到在哪裏放置,這樣我可以創造一個優美的錯誤信息,而不是我發現了捕致命錯誤。下面是我當前的代碼:

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 = "[email protected]"; //this is email is NOT in Constant Contact 
ccdeleteuser($emailtotry); 

現在如果我運行此我得到以下錯誤:

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

任何幫助表示讚賞!

+0

你應該檢查'$ SearchContact'是否是一個數組;那麼你不必擔心異常。 –

+0

DUP:http://stackoverflow.com/questions/2468487/how-can-i-catch-a-catchable-fatal-error-on-php-type-hinting – xdazz

回答

1

做到這一點,正確的方法是先測試空:

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 ...趕上,你可以使它看起來像這樣:

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作爲最後的可能手段。

+0

謝謝您的回答,第一個非常完美!這種情況下,你在做「試着抓住」這樣的事情時會感到很茫然,你忘記了有一種更簡單(更有效)的方式! –