【问题标题】:Laravel - catch the custom abort messageLaravel - 捕获自定义中止消息
【发布时间】:2017-10-03 02:56:05
【问题描述】:

我正在使用中止功能从我的服务层发送自定义异常消息。

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...)

【问题讨论】:

    标签: laravel abort custom-errors


    【解决方案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 响应。

    让我知道它现在是否适合你:)

    【讨论】:

    • 这个异常没有被捕获。
    • 编辑了我的答案。
    • 我尝试了和你一样的方法,写了一个测试中止函数。但现在它没有捕获任何非常奇怪的异常(一般、guzzle 或 symfony)。
    • 我添加了更多代码。我应该提到我的服务和控制器在不同的应用程序中。希望这会有所帮助。
    • 编辑了我的答案
    猜你喜欢
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 2014-05-31
    • 2017-06-28
    • 2017-12-13
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多