2016-08-20 145 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); 
    }