我使用中止功能从我的服务层发送自定义异常消息。
if($max_users < $client->users()->count()){
return abort(401, "Max User Limit Exceeded");
}
但是如何在我的控制器中捕获此消息,该控制器位于不同的应用程序中
try{
$clientRequest = $client->request(
'POST',
"api/saveClientDetails",
[
'headers' => [
'accept' => 'application/json',
'authorization' => 'Bearer ' . $user['tokens']->access_token
],
'form_params' => $data,
]
);
} catch ( \GuzzleHttp\Exception\ClientException $clientException ){
switch($clientException->getCode()){
case 401:
\Log::info($clientException->getCode());
\Log::info($clientException->getMessage());
abort(401);
break;
default:
abort(500);
break;
}
}
以上代码为消息打印以下内容:
但它打印
Client error: `POST http://project-service.dev/api/saveClientDetails` resulted in a `401 Unauthorized` response:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="robots" content="noindex,nofollow (truncated...)
答案 0 :(得分:1)
当你应该捕获Symfony HttpException时,你正试图捕获Guzzle异常。也许尝试这样的事情:
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e)
{
\Log::info($e->getMessage());
}
根据您的评论,我尝试了以下内容:
public function test()
{
try
{
$this->doAbort();
}
catch (\Symfony\Component\HttpKernel\Exception\HttpException $e)
{
dd($e->getStatusCode(), $e->getMessage());
}
}
public function doAbort()
{
abort(401, 'custom error message');
}
,输出为:
401
"custom error message"
根据您的评论,以下是它对我有用的方式。
Route::get('api', function() {
return response()->json([
'success' => false,
'message' => 'An error occured'
], 401);
});
Route::get('test', function() {
$client = new \GuzzleHttp\Client();
try
{
$client->request('GET', 'http://app.local/api');
}
catch (\Exception $e)
{
$response = $e->getResponse();
dd($response->getStatusCode(), (string) $response->getBody());
}
});
这将输出状态代码和正确的错误消息。如果您使用abort
,它仍会返回完整的HTML响应。更好的方法是返回格式良好的JSON响应。
让我知道它现在是否适合你:)