Laravel-捕获自定义中止消息
我正在使用abort函数从我的服务层发送自定义异常消息Laravel-捕获自定义中止消息,laravel,abort,custom-errors,Laravel,Abort,Custom Errors,我正在使用abort函数从我的服务层发送自定义异常消息 if($max_users < $client->users()->count()){ return abort(401, "Max User Limit Exceeded"); } 上述代码为消息打印以下内容: 但它会打印出来 Client error: `POST http://project-service.dev/api/saveClientDetails` resulted in a `401 Unau
if($max_users < $client->users()->count()){
return abort(401, "Max User Limit Exceeded");
}
上述代码为消息打印以下内容:
但它会打印出来
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...)
当您应该捕获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响应
让我知道它现在是否适用于您:未捕获此异常。编辑了我的答案。我尝试了与您相同的方法,编写了测试中止函数。但是现在它没有捕捉到任何异常general、guzzle或symfony,这很奇怪。我添加了更多代码。我应该提到我的服务和控制器在不同的应用程序中。希望这有帮助。编辑了我的答案
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());
}
});