2013-08-07 33 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'为你工作增加了一些信息这是关于名称空间和解决类名称) –