2013-08-07 32 views
0

我想讓我的api異常,但我不明白如何做到這一點。 這是我的代碼throw APIException Facebook api php

public function facebook($link){ 

    if(!$link || !trim($link) != ""){ 
     return false; 
    } 

    $config = array(
      'appId'=>$this->keys['facebook']['id'], 
      'secret'=>$this->keys['facebook']['secret'], 
      'fileUpload'=>false 
    ); 

    $facebook = new Facebook($config); 


    $start = strrpos($link, '/', -1); 
    $end = strripos($link, '?', -1); 
    $end = ($end)?$end:strlen($link); 

    $pageId = ($end == strlen($link))?substr($link, $start + 1):substr($link, $start + 1, $end - strlen($link)); 

    try { 
     $pagefeed = $facebook->api("/" . $pageId . "/feed"); 
    } 
    catch (FacebookApiException $e){ 
     return false; 
    } 

    //set datetime 
    foreach ($pagefeed['data'] as $key => $post){ 
     $pagefeed['data'][$key]['datetime'] = new \DateTime($post['created_time']); 
    } 

    return $pagefeed; 
} 

所以我想在例外的情況下,返回false。

我得到爲例:

BaseFacebook ->throwAPIException (array('error' => array('message' => '(#803) Some of the aliases you requested do not exist: lkdsgfkqdjgflkdshbf', 'type' => 'OAuthException', 'code' => '803'))) 

感謝您的幫助

回答

2

既然你已經評論說,你正在使用symfony和你固定使用catch(\Exception $e)你可能要考慮的類型提示添加以下內容到文件的頂部:

use \APIException; 

設置APIException作爲別名\APIExceptionAlso check this link。沒有使用FB API,我不知道它是否仍然相關,但假設Facebook API存儲在您的供應商目錄中,那麼在使用Facebook API時必須指定正確的名稱空間。
\Exception工作原因僅僅是因爲,如鏈接頁面所示,APIException類從\Exception基類繼承而來,因此type-hint起作用。這並不重要,但通常在正確的地方找到正確的例外情況會更好。

引發異常,並使用catch塊捕獲它。儘管如此,它仍然捕獲了方法的範圍,當該方法返回時垃圾回收(Garbage Collected)。 Exception isntance不再退出。
通常,如果您想訪問方法外的異常(很可能在調用該方法的代碼中),您只是不會捕獲該異常。從facebook方法取出try-catch和做到這一點:

//call method: 
try 
{ 
    $return = $instance->facebook($someLink); 
} 
catch (APIException $e) 
{ 
    $return = false;//exception was thrown, so the return value should be false 
    var_dump($e);//you have access to the exception here, too 
} 

捕獲異常,並沒有做任何事的(你正在追趕,但返回false,不知道爲什麼方式)被認爲是不好的做法。
如果你想避免包裝所有這些調用你的facebook方法在一個try-catch,你可以做這樣的事情,太:

//in class containing facebook method: 
private $lastException = null; 
public function getLastException() 
{ 
    return $this->lastException; 
} 

現在,您可以facebook方法的catch塊更改爲:

catch(APIException $e) 
{ 
    $this->lastException = $e; 
    return false; 
} 

而且做這樣的事情:

$return = $instance->facebook($link); 
if ($return === false) 
{ 
    var_dump($instance->getLastException()); 
    exit($instance->getLastException()->getMessage()); 
} 
+0

謝謝您的回答,但我真的不明白爲什麼例外是不是在我的CA拋出se,我的頁面返回500內部服務器錯誤 - FacebookApiException(我正在使用Symfony2) – Ajouve

+0

我找到了解決方案,我不得不趕上\ symfony – Ajouve

+0

@ant的異常:爲什麼'\ Exception'爲你工作增加了一些信息這是關於名稱空間和解決類名稱) –