2012-11-01 77 views
1

你對這個作品有什麼看法?這是錯的嗎?如何正確地做到這一點?您認爲在catch中嵌套try/catch語句有什麼用?

$graph_url = 'https://graph.facebook.com/me?access_token=' . $result['access_token']; 
$fb_user = json_decode(file_get_contents($graph_url)); 
try { 
    $user = new Model_User($fb_user->username); 
    $user_meta = new Model_User_Meta ($user->get ('user_id')); 
    $user_meta->set_user_meta('_facebook_id', $fb_user->id); 
    $user_meta->set_user_meta('_last_logged_in', 'current_timestamp'); 
    $user_meta->save(); 
} catch (Exception $e) { 
    if ($e->getCode() === 0){ 
     $password = Helper_Password::generate_password(); 
     $hash = Helper_Password::hash_string($password); 
     try { 
      $user = new Model_User(); 
      $user->set('user_name', $fb_user->username); 
      $user->set('user_pass', $hash); 
      $user->set('user_email', $fb_user->email); 
      $user->set('user_status',($fb_user->verified ? 'active' : 'inactive')); 
      $user->set('display_name', $fb_user->name); 
      $status = $user->save(); 
      $user_meta = new Model_User_Meta ($status->user_id); 
      $user_meta->set_user_meta('_facebook_id', $fb_user->id); 
      $user_meta->set_user_meta('_last_logged_in', 'current_timestamp'); 
      $user_meta->save(); 
     } catch (Exception $e) { 
      throw $e; 
     } 
    } else { 
     throw $e; 
    } 
} 
+0

在http://codereview.stackexchange.com上可以嗎? – fgb

+1

也許值得留下一個鏈接爲什麼這是嚴重問,這可能是更多的幫助,而不僅僅是建議另一個網站:http://stackoverflow.com/faq#dontask – hakre

回答

1

嘗試恢復期間捕獲,然後拋出一個異常,如果你必須罰款。

但是你在這裏的代碼中有一些含糊之處。你打算扔哪個$e?最初的例外,還是新的例外?如果你想拋出原始異常,那麼你不應該在你的第二個catch語句覆蓋$e

} catch (Exception $e) { 
    if ($e->getCode() === 0){ 
     try { 
      // try recovering here? 
     } catch (Exception $otherException) { 
      throw $e; // throw the original exception instead of the new one 
     } 
    } else { 
     throw $e; 
    } 
} 

如果你想拋出新的異常,你並不需要在所有的內抓住...

} catch (Exception $e) { 
    if ($e->getCode() === 0){ 
     // try recovering here, and let the exception fly as they will 
    } else { 
     throw $e; 
    } 
} 
相關問題