How to send POST request with basic authentication and exception handling

Most of the times the POST request endpoints are protected by basic authentication. Accessing them might give errors such as access denied or 500 internal server error. Here is post request snippet in Guzzle to handle requests in such cases.

try {
      $client = \Drupal::httpClient();
      $request = $client->post('/example-post-url/', [
        'auth' => ['username', 'password'],
        'json' => [
          'data' => $data,
      $response = json_decode($request->getBody(), TRUE);
    catch (RequestException $error) {
     $error_message =  $error->getMessage();