1

この構成についてどう思いますか?違いますか?適切に行う方法は?

$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;
    }
}
4

1 に答える 1

1

キャッチ中に回復を試み、必要に応じて例外をスローしても問題ありません。

しかし、ここのコードにはあいまいさがあります。どれ$eを投げるつもりだったの?元の例外ですか、それとも新しい例外ですか? 元の例外をスローしたい場合$eは、2 番目の catch ステートメントでオーバーライドしないでください。

} 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;
    }
}
于 2012-11-01T18:40:52.440 に答える