How to show a nice message to the user when an error occurs in using Guzzle with Laravel

How to show a nice message to the user when an error occurs in using Guzzle with Laravel

How to show a nice message to the user when an error occurs in using Guzzle with Laravel

Hello there, everyone. Have you ever gotten an unsightly Exception when trying to post, receive, put, or remove data to an external API and getting a 500 or 404 error? Today you’ve come to the proper place; after reading this, you’ll be able to display a pleasant message to your users if any of these mistakes occur.

How to show a nice message to the user when an error occurs in using Guzzle with Laravel

When making a request to external API using guzzle to solve this problem you will need to catch the Exception by following the steps below.

  1. Prepare your request using Guzzle, I believe you know or have set it up already
  2. Make a post or get request to your external API
    public function create(Request $request) {
    $input = $request->all();
    try {
        $client = new Client();
        $headers = ['API-Key' => env('API_KEY')];
        $url = 'api/post/create';
        $response = $client->request('POST', $url, ['headers' => $headers, 'query' => $input]);
        $res = json_decode($response->getBody());
//here will catch error to aviod ugly message to users  
    } catch (\GuzzleHttp\Exception\RequestException $res) {
        if ($res->hasResponse()) {
            $response = $res->getResponse();
            if ($response->getStatusCode() == 500) {
                abort(500);
            } if ($response->getStatusCode() == 404) {
                abort(404);
            }
        }
    }
}

Congrats , you have saved your users from seeing that ugly message . Share and comment

Be the first to comment

Leave a Reply

Your email address will not be published.


*