2016-08-20 7 views
0

私はHalo 5 APIを使用しており、ユーザーはゲーマータグに登録できます。彼らはログインすることができます。ログインすると、プロフィールにアクセスしてHalo 5の統計情報を調べることができます。しかし、明らかに一部のユーザーは正規のゲーマータグを入力することはありません。そして、それは私のコントローラでプロファイルのビューを返すいくつかの検証が必要だった。ここでコントローラーで404エラーが発生していないか確認します。ラベール5

は、コントローラの簡単な例です:

public function index ($slug) { 

     // Emblem URL. 
     $getPlayerEmblemImage = app('App\Http\Controllers\Api\GetGeneralStatsController')->getPlayerEmblemImage($slug); 

     // Get General Player Arena Stats 
     $playerGeneralStats = app('App\Http\Controllers\Api\GetGeneralStatsController')->getPlayerArenaStats($slug); 
     $playerGeneralStatsArray = $this->getPlayerGeneralStatsArray($playerGeneralStats); 

     // Get the Spartan Rank and XP 
     $spartanRank = json_decode($playerGeneralStatsArray['SpartanRank'], true); 
     $XP = json_decode($playerGeneralStatsArray['Xp'], true); 
     $Gamer_Tag = json_encode($playerGeneralStatsArray['Gamer_Tag'], true); 

     $user = User::whereSlug($slug)->firstOrFail(); 

     return view('profile.index', 
      compact(
       'user', 
       'spartanRank', 
       'XP', 
       'getPlayerEmblemImage', 
       'Gamer_Tag', 
      ) 
     ); 
    } 

私の問題は、ユーザが存在しない場合、それはこのエラーをスローし、次のとおりです。

ClientException in RequestException.php line 107: Client error: GET https://www.haloapi.com/profile/h5/profiles/some%20useer/spartan resulted in a 404 Not Found response:

は、どのように私はいくつかのチェックを行うことができ、そのプレイヤーが見つからない場合は別の結果を返しますか?

多分このような何か?

public function index ($slug) { 

    if (// Doesnt exist, show this) { 
    // do some other code here 
    return view('profile.index', compact('user')) 

    } else { 

    // Code here.... 

return view('profile.index', 
      compact(
       'user', 
       'spartanRank', 
      )) 
    } 

} 

答えて

1

ここで例外処理を使用できると思います。お使いのコントローラ

使用GuzzleHttp \例外の\ ClientExceptionで

try{ 
    // Code here.... 

return view('profile.index', 
      compact(
       'user', 
       'spartanRank', 
      )) 
} 
} catch(ClientException $exception) { 
{ 
    // do some other code here 
    return view('profile.index', compact('user')) 
} 

インポートuse GuzzleHttp\Exception\ClientException;

+0

**私はあなたが**あなたがキャッチしたい特定の例外と例外を交換して言うとき – David

+0

は、あなたがそのコメントに何を意味することにしてみましょうか? – David

+0

例外の代わりに 'NotFoundException'を使用してください。 – jaysingkar

0

アプリケーション/例外/ Handler.php

の変更コード
public function render($request, Exception $e) 
    { 
     // Flash a success message saying you have successfully registered. 
     flash()->error('Error', 'That player has not played Halo, or does not exist.'); 

     return redirect()->back(); 

     // return parent::render($request, $e); 
    } 
関連する問題