2016-08-20 141 views
0

我使用的是Halo 5 API,用戶可以使用他們的玩家標籤進行註冊。當他們這樣做時,他們可以登錄,當他們登錄時,他們可以去他們的個人資料查找他們的光環5的統計。但顯然有些用戶不會輸入合法的玩家標籤。那就是我需要在控制器中進行一些驗證,以返回配置文件的視圖。檢查控制器中是否有404響應錯誤 - Laravel 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

我想你可以在這裏使用異常處理。

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;在控制器

使用GuzzleHttp \異常\ ClientException;

+0

讓我試試 – David

+0

你在這一評論的意思,當你說**替換你想捕獲特定的異常異常做**? – David

+0

而不是異常,使用'NotFoundException' – jaysingkar

0

明白了。在app /異常變化碼/ 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); 
    }