Handle Partial Failure

Java
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.errorhandling;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v1.errors.GoogleAdsError;
import com.google.ads.googleads.v1.errors.GoogleAdsException;
import com.google.ads.googleads.v1.resources.AdGroup;
import com.google.ads.googleads.v1.services.AdGroupOperation;
import com.google.ads.googleads.v1.services.AdGroupServiceClient;
import com.google.ads.googleads.v1.services.MutateAdGroupResult;
import com.google.ads.googleads.v1.services.MutateAdGroupsResponse;
import com.google.ads.googleads.v1.utils.ErrorUtils;
import com.google.ads.googleads.v1.utils.ResourceNames;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

/**
 * Shows how to handle partial failures. There are several ways of detecting partial failures. This
 * highlights the top main detection options: empty results and error instances.
 *
 * <p>Access to the detailed error (<code>GoogleAdsFailure</code>) for each error is via a Any
 * proto. Deserializing these to retrieve the error details is may not be immediately obvious at
 * first, this example shows how to convert Any into <code>GoogleAdsFailure</code>.
 *
 * <p>Additionally, this example shows how to produce an error message for a specific failed
 * operation by looking up the failure details in the <code>GoogleAdsFailure</code> object.
 */
public class HandlePartialFailure {

  private static class HandlePartialFailureParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;
  }

  public static void main(String[] args) throws InvalidProtocolBufferException {
    HandlePartialFailureParams params = new HandlePartialFailureParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID");
      params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID");
    }
    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new HandlePartialFailure().runExample(googleAdsClient, params.customerId, params.campaignId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
    }
  }

  /** Runs the example. */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId)
      throws InvalidProtocolBufferException {
    // This AdGroup should be created successfully - assuming the campaign in the params exists.
    AdGroup group1 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
            .setName(StringValue.of("Valid AdGroup: " + System.currentTimeMillis()))
            .build();
    // This AdGroup will always fail - campaign ID 0 in resource names is never valid.
    AdGroup group2 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, 0L)))
            .setName(StringValue.of("Broken AdGroup: " + System.currentTimeMillis()))
            .build();
    // This AdGroup will always fail - duplicate ad group names are not allowed.
    AdGroup group3 =
        AdGroup.newBuilder()
            .setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
            .setName(group1.getName())
            .build();

    AdGroupOperation op1 = AdGroupOperation.newBuilder().setCreate(group1).build();
    AdGroupOperation op2 = AdGroupOperation.newBuilder().setCreate(group2).build();
    AdGroupOperation op3 = AdGroupOperation.newBuilder().setCreate(group3).build();

    try (AdGroupServiceClient service =
        googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
      // Issues the mutate request, setting partialFailure=true.
      MutateAdGroupsResponse response =
          service.mutateAdGroups(
              String.valueOf(customerId),
              Arrays.asList(op1, op2, op3),
              // Sets partial failure to true.
              true,
              // Sets validate only to false.
              false);

      // Checks for existence of any partial failures in the response.
      if (response.hasPartialFailureError()) {
        System.out.println("Partial failures occurred. Details will be shown below.");
      } else {
        System.out.println("All operations completed successfully. No partial failures to show.");
        return;
      }

      // Finds the failed operations by looping through the results.
      int operationIndex = 0;
      for (MutateAdGroupResult result : response.getResultsList()) {
        if (ErrorUtils.isPartialFailureResult(result)) {
          // May throw on this line. Most likely this means the wrong version of the ErrorUtils
          // class has been used.
          for (GoogleAdsError error :
              ErrorUtils.getGoogleAdsErrors(operationIndex, response.getPartialFailureError())) {
            System.out.printf("Operation %d failed with error: %s%n", operationIndex, error);
          }
        } else {
          System.out.printf("Operation %d succeeded.%n", operationIndex);
        }
        ++operationIndex;
      }
    }
  }
}
Python
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This shows how to handle responses that may include partial_failure errors.
"""

from __future__ import absolute_import

import argparse
import six
import sys
import uuid

from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.errors import GoogleAdsException


def main(client, customer_id, campaign_id):
    ad_group_service = client.get_service('AdGroupService', version='v1')
    campaign_service = client.get_service('CampaignService', version='v1')
    resource_name = campaign_service.campaign_path(customer_id, campaign_id)
    invalid_resource_name = campaign_service.campaign_path(customer_id, 0)
    ad_group_operations = []

    # This AdGroup should be created successfully - assuming the campaign in
    # the params exists.
    ad_group_op1 = client.get_type('AdGroupOperation', version='v1')
    ad_group_op1.create.name.value = 'Valid AdGroup: %s' % uuid.uuid4()
    ad_group_op1.create.campaign.value = resource_name
    ad_group_operations.append(ad_group_op1)

    # This AdGroup will always fail - campaign ID 0 in resource names is
    # never valid.
    ad_group_op2 = client.get_type('AdGroupOperation', version='v1')
    ad_group_op2.create.name.value = 'Broken AdGroup: %s' % (uuid.uuid4())
    ad_group_op2.create.campaign.value = invalid_resource_name
    ad_group_operations.append(ad_group_op2)

    # This AdGroup will always fail - duplicate ad group names are not allowed.
    ad_group_op3 = client.get_type('AdGroupOperation', version='v1')
    ad_group_op3.create.name.value = (ad_group_op1.create.name.value)
    ad_group_op3.create.campaign.value = resource_name
    ad_group_operations.append(ad_group_op3)

    try:
        # Issue a mutate request, setting partial_failure=True.
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, ad_group_operations, partial_failure=True)
    except GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)
    else:
        # Check for existence of any partial failures in the response.
        if ad_group_response.partial_failure_error:
            print('Partial failures occurred. Details will be shown below.\n')
            partial_failures = get_partial_failure_messages(
                client, ad_group_response)

            for error in partial_failures:
                # Construct and print a string that details which element in
                # the above ad_group_operations list failed (by index number)
                # as well as the error message and error code.
                print('A partial failure at index %d occured.\n'
                      'Error message: %s\nError code: %s' % (
                          error.location.field_path_elements[0].index.value,
                          error.message, error.error_code))
        else:
            print('All operations completed successfully. No partial failure '
                  'to show.')

        # In the list of results, operations from the ad_group_operation list
        # that failed will be represented as empty messages. This loop detects
        # such empty messages and ignores them, while printing information about
        # successful operations.
        for message in ad_group_response.results:
            # Empty messages will have a byte size of zero.
            if message.ByteSize() == 0:
                continue

            print('Created ad group with resource_name: %s.' % (
                message.resource_name))


def get_partial_failure_messages(client, response):
    """Get a list of all partial failure error objects for a given response.

    Shows how to retrieve partial_failure errors from a response message (in
    the case of this example the message will be of type MutateAdGroupsResponse)
    and how to unpack those errors to GoogleAdsError instances. As an example,
    a GoogleAdsError object from this example will be structured similar to:

    error_code {
      range_error: TOO_LOW
    }
    message: "Too low."
    trigger {
      string_value: ""
    }
    location {
      field_path_elements {
        field_name: "operations"
        index {
          value: 1
        }
      }
      field_path_elements {
        field_name: "create"
      }
      field_path_elements {
        field_name: "campaign"
      }
    }

    Args:
        client: an initialized GoogleAdsClient.
        response: a MutateAdGroupsResponse instance.
    Returns:
        A list of GoogleAdsError instances each relating to an individual
        failure from the given list of partial failures.
    """
    # Retrieve the serialized list of errors off of the response message.
    error_detail = response.partial_failure_error.details[0].value
    # Retrieve the GoogleAdsFailure class from the client
    google_ads_failure = client.get_type('GoogleAdsFailure', version='v1')
    # Parse the string into a GoogleAdsFailure message instance.
    err_object = google_ads_failure.FromString(error_detail)
    return err_object.errors


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage()

    parser = argparse.ArgumentParser(
        description='Adds an ad group for specified customer and campaign id.')
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=six.text_type,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-i', '--campaign_id', type=six.text_type,
                        required=True, help='The campaign ID.')
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.campaign_id)
PHP
<?php
/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 namespace Google\Ads\GoogleAds\Examples\ErrorHandling;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V1\GoogleAdsErrors;
use Google\Ads\GoogleAds\Util\V1\GoogleAdsFailures;
use Google\Ads\GoogleAds\Util\V1\PartialFailures;
use Google\Ads\GoogleAds\Util\V1\ResourceNames;
use Google\Ads\GoogleAds\V1\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V1\Resources\AdGroup;
use Google\Ads\GoogleAds\V1\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V1\Services\MutateAdGroupsResponse;
use Google\ApiCore\ApiException;
use Google\Protobuf\StringValue;

/**
 * Shows how to handle partial failures. There are several ways of detecting partial failures. This
 * highlights the top main detection options: empty results and error instances.
 *
 * <p>Access to the detailed error (<code>GoogleAdsFailure</code>) for each error is via a Any
 * proto. Deserializing these to retrieve the error details is may not be immediately obvious at
 * first, this example shows how to convert Any into <code>GoogleAdsFailure</code>.
 *
 * <p>Additionally, this example shows how to produce an error message for a specific failed
 * operation by looking up the failure details in the <code>GoogleAdsFailure</code> object.
 */
class HandlePartialFailure
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     * @param int $campaignId a campaign ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, $customerId, $campaignId)
    {
        $response = self::createAdGroups($googleAdsClient, $customerId, $campaignId);
        self::checkIfPartialFailureErrorExists($response);
        self::printResults($response);
    }

    /**
     * Create ad groups by enabling partial failure mode.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     * @param int $campaignId a campaign ID
     * @return MutateAdGroupsResponse
     */
    private static function createAdGroups(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $campaignId
    ) {
        $campaignResourceName =
            new StringValue(['value' => ResourceNames::forCampaign($customerId, $campaignId)]);

        // This ad group should be created successfully - assuming the campaign in the params
        // exists.
        $adGroup1 = new AdGroup([
            'name' => new StringValue(['value' => 'Valid AdGroup #' . uniqid()]),
            'campaign' => $campaignResourceName
        ]);

        // This ad group will always fail - campaign ID 0 in the resource name is never valid.
        $adGroup2 = new AdGroup([
            'name' => new StringValue(['value' => 'Broken AdGroup #' . uniqid()]),
            'campaign' => ResourceNames::forCampaign($customerId, 0)
        ]);

        // This ad group will always fail - duplicate ad group names are not allowed.
        $adGroup3 = new AdGroup([
            'name' => $adGroup1->getName(),
            'campaign' => $campaignResourceName
        ]);

        $operations = [];

        $adGroupOperation1 = new AdGroupOperation();
        $adGroupOperation1->setCreate($adGroup1);
        $operations[] = $adGroupOperation1;

        $adGroupOperation2 = new AdGroupOperation();
        $adGroupOperation2->setCreate($adGroup2);
        $operations[] = $adGroupOperation2;

        $adGroupOperation3 = new AdGroupOperation();
        $adGroupOperation3->setCreate($adGroup3);
        $operations[] = $adGroupOperation3;

        // Issues the mutate request, enabling partial failure mode.
        $adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
        return $adGroupServiceClient->mutateAdGroups(
            $customerId,
            $operations,
            ['partialFailure' => true]
        );
    }

    /**
     * Check if there exists partial failure error in the given mutate ad group response.
     *
     * @param MutateAdGroupsResponse $response the mutate ad group response
     */
    private static function checkIfPartialFailureErrorExists(MutateAdGroupsResponse $response)
    {
        if (!is_null($response->getPartialFailureError())) {
            printf("Partial failures occurred. Details will be shown below.%s", PHP_EOL);
        } else {
            printf(
                "All operations completed successfully. No partial failures to show.%s",
                PHP_EOL
            );
        }
    }

    /**
     * Print results of the given mutate ad group response. For those that are partial failure,
     * print all their errors with corresponding operation indices. For those that succeeded, print
     * the resource names of created ad groups.
     *
     * @param MutateAdGroupsResponse $response the mutate ad group response
     */
    private static function printResults(MutateAdGroupsResponse $response)
    {
        // Finds the failed operations by looping through the results.
        $operationIndex = 0;
        foreach ($response->getResults() as $result) {
            /** @var AdGroup $result */
            if (PartialFailures::isPartialFailure($result)) {
                $errors = GoogleAdsErrors::fromStatus(
                    $operationIndex,
                    $response->getPartialFailureError()
                );
                foreach ($errors as $error) {
                    printf(
                        "Operation %d failed with error: %s%s",
                        $operationIndex,
                        $error->getMessage(),
                        PHP_EOL
                    );
                }
            } else {
                printf(
                    "Operation %d succeeded: ad group with resource name '%s'.%s",
                    $operationIndex,
                    $result->getResourceName(),
                    PHP_EOL
                );
            }
            $operationIndex++;
        }
    }
}

HandlePartialFailure::main();
Ruby
# Encoding: utf-8
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example shows how to deal with partial failures

require 'optparse'
require 'google/ads/google_ads'

def add_keywords(customer_id, ad_group_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  criteria = [
    "mars cruise",
    "inv@lid cruise",
    "venus cruise",
    "b(a)d keyword cruise"
  ].map { |keyword|
    criterion = client.resource(:AdGroupCriterion)
    criterion.ad_group = client.wrapper.string(
      client.path.ad_group(customer_id, ad_group_id),
    )
    criterion.keyword = client.resource(:KeywordInfo)
    criterion.keyword.text = client.wrapper.string(keyword)
    criterion.keyword.match_type = :EXACT
    criterion
  }

  operations = criteria.map { |criterion|
    operation = client.operation(:AdGroupCriterion)
    operation["create"] = criterion
    operation
  }

  criterion_service = client.service(:AdGroupCriterion)
  response = criterion_service.mutate_ad_group_criteria(
    customer_id,
    operations,
    partial_failure: true,
  )

  response.results.each_with_index do |criterion, i|
    if criterion.resource_name != ""
      puts("operations[#{i}] succeeded: Created ad group criterion with id #{criterion.resource_name}")
    end
  end

  failures = client.decode_partial_failure_error(response.partial_failure_error)
  failures.each do |failure|
    failure.errors.each do |error|
      human_readable_error_path = error
        .location
        .field_path_elements
        .map { |location_info|
          if location_info.index
            "#{location_info.field_name}[#{location_info.index}]"
          else
            "#{location_info.field_name}"
          end
        }.join(" > ")

      errmsg =  "error occured creating criterion #{human_readable_error_path}" \
        " with value: #{error.trigger.string_value}" \
        " because #{error.message.downcase}"
      puts errmsg
    end
  end
end

if __FILE__ == $PROGRAM_NAME
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-A', '--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
      options[:ad_group_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_keywords(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:ad_group_id),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
        e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

Google Ads API
Google Ads API
Need help? Visit our support page.