2013-10-03 111 views
1

我需要能夠捕獲錯誤。我有以下代碼PHP捕獲錯誤

if($call['status_id'] != '' && $call['datetime_required'] != '') 
{ 
    //do stuff 
} 
else 
{ 
    // tell them how it failed 
} 

我該如何去顯示ti失敗的部分。因此,例如,我可以即

return 'You did not fill in the field $errorField'; 

$errorField 

是的,如果檢查其所失敗返回一個動態的錯誤消息。

UPDATE

我目前的代碼,像這樣

if($call['status_id'] != '') 
{ 
    if ($call['datetime_required'] != '') 
    { 
     //do stuff 
    } 
    else 
    { 
     // tell them it failed due to the second condition 
    } 
} 
else 
{ 
    // tell them it failed due to the first condition 
} 

但想不同的地方TI沒有做檢查的一行,並更改消息。

注意@jack在此更新之前已經發布了他的答案。

+0

如果這是一個函數,你肯定可以返回一個字符串包含錯誤信息,並檢查是否返回值=== TRUE,否則假定存在錯誤情況和返回值錯誤。 –

+0

是的,這是一個類方法 –

+0

是否所有的數據被驗證存儲在類成員,可以迭代? –

回答

2
if($call['status_id'] != '') 
{ 
    if ($call['datetime_required'] != '') 
     //do stuff 
    } 
    else 
    { 
     // tell them it failed due to the second condition 
    } 
} 
else 
{ 
    // tell them it failed due to the first condition 
} 
+1

我有點新,我喜歡這個解決方案,因爲它提供了什麼失敗與一攬子「失敗」的聲明的粒度。它更加用戶友好。 –

+0

我一直這樣做,但我的一位同事建議,這可能會膨脹代碼太多,並導致太多嵌套的if語句。因此,一次完成所有檢查然後返回錯誤可能會更好。 –

+0

@JonPaulH我們在談論多少個領域? –

3

我不確定我是否完全理解你,你的意思是這樣的?

function check($call, $req_fields) { 
    $failed = array(); 
    foreach($req_fields as $field) { 
     if(!$call[$field]) { 
      $failed[] = $field; 
     } 
    } 
    if(count($failed)) { 
     return join(', ', $failed) . ' are required.'; 
    } 
    return 'success?' ; 
} 

$message = check($call, array('status_id', 'datetime_required'));