處理 API 錯誤

向 Google Ads API 傳送要求時,可能會因為各種原因而失敗。舉例來說,您可能提供無效的引數,或是帳戶建立新廣告活動的數量已達上限。在這種情況下,API 會傳回錯誤訊息,讓您瞭解發生錯誤的原因。

本指南說明如何讀取及處理 API 錯誤,以便建構更完善的應用程式。

錯誤結構

如果您使用我們的用戶端程式庫,API 錯誤會以例外狀況的形式顯示。這些例外狀況包含詳細資料,可協助您瞭解發生錯誤的原因。

Google Ads API 會以標準格式傳回錯誤資訊。如果發生錯誤,回應會包含 GoogleAdsFailure 物件。這個物件包含個別 GoogleAdsError 物件的清單,每個物件都詳細說明特定錯誤。

每個 GoogleAdsError 物件都會提供:

除了錯誤清單之外,GoogleAdsFailure 還包含 requestId,這是導致錯誤的 API 要求的專屬 ID。

錯誤範例

以下是 JSON 格式的錯誤範例。這項錯誤表示要求缺少索引 0ad_group name 欄位。

{
  "code": 3,
  "message": "Request contains an invalid argument.",
  "details": [
    {
      "@type": "type.googleapis.com/google.ads.googleads.v22.errors.GoogleAdsFailure",
      "errors": [
        {
          "errorCode": {
            "requestError": "REQUIRED_FIELD_MISSING"
          },
          "message": "Required field is missing",
          "location": {
            "fieldPathElements": [
              {
                "fieldName": "ad_group",
                "index": 0
              },
              {
                "fieldName": "name"
              }
            ]
          }
        }
      ],
      "requestId": "unique_request_id_12345"
    }
  ]
}

如要進一步瞭解 API 錯誤,請參閱我們的指南

用戶端程式庫範例

下一節說明如何在各種用戶端程式庫中處理錯誤。

Java

try {
  // Make an API call.
  ...
} 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);
  }
}

C#

try
{
    // Make an API call.
    ...
}
catch (GoogleAdsException e)
{
    Console.WriteLine($"Request with ID '{e.RequestId}' has failed.");
    Console.WriteLine("Google Ads failure details:");

    foreach (GoogleAdsError error in e.Failure.Errors)
    {
        Console.WriteLine($"{error.ErrorCode}: {error.Message}");
    }
}

PHP

try {
  // Make an API call.
  ...
} 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
        );
    }
}

Python

try:
    # Make an API call.
    ...
except GoogleAdsException as ex:
    print(
        f"Request with ID '{ex.request_id}' failed with status "
        f"'{ex.error.code().name}' and includes the following errors:"
    )
    for error in ex.failure.errors:
        print(f"\tError with message '{error.message}' and code '{error.error_code}'.")

Ruby

begin
    # Make an API call.
    ...
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    puts "API call failed with request ID: #{e.request_id}"
    e.failure.errors.each do |error|
        puts "\t#{error.error_code}: #{error.message}"
    end
end

Perl

# Try sending a mutate request to add the ad group ad.
...
if ($response->isa("Google::Ads::GoogleAds::GoogleAdsException")) {
  printf "Google Ads failure details:\n";
  foreach my $error (@{$response->get_google_ads_failure()->{errors}}) {
    printf "\t%s: %s\n", [keys %{$error->{errorCode}}]->[0], $error->{message};
  }
}

如何擷取記錄

如要排解錯誤,請擷取 Google Ads API 伺服器傳回的錯誤記錄,並檢查內容。請按照下列操作說明啟用記錄功能,並擷取 API 記錄。

Java

如需相關操作說明,請參閱 Java 用戶端程式庫記錄指南

C#

如要初始化記錄功能,請在發出任何 API 呼叫前,在 Main 方法中加入下列程式碼。這可確保程式庫會為應用程式發出的所有 API 呼叫產生記錄。

using Google.Ads.GoogleAds.Util;
...

// Detailed logs.
TraceUtilities.Configure(TraceUtilities.DETAILED_REQUEST_LOGS_SOURCE,
    "/path/to/your/logs/details.log", System.Diagnostics.SourceLevels.All);

// Summary logs.
TraceUtilities.Configure(TraceUtilities.SUMMARY_REQUEST_LOGS_SOURCE,
    "/path/to/your/logs/summary.log", System.Diagnostics.SourceLevels.All);

如需其他選項,請參閱 .NET 程式庫記錄指南

PHP

您可以在用戶端程式庫的 google_ads_php.ini 檔案中設定記錄設定。將 logLevel 設為 NOTICE,開始擷取詳細錯誤記錄。

[LOGGING]
; Optional logging settings.
logFilePath = "path/to/your/file.log"
logLevel = "NOTICE"

如需操作說明,請參閱 PHP 用戶端程式庫記錄指南

Python

您可以在用戶端程式庫的 google-ads.yaml 檔案中設定記錄設定。將記錄層級設為 DEBUG,即可開始擷取詳細錯誤記錄。

如需其他選項,請參閱 Python 程式庫記錄指南

Ruby

您可以在用戶端程式庫的 google_ads_config.rb 檔案中設定記錄設定。將記錄層級設為 INFO,即可開始擷取詳細錯誤記錄。

如需其他選項,請參閱 Ruby 程式庫記錄指南

Perl

如要初始化記錄功能,請在發出任何 API 呼叫前,在 Perl 指令碼中加入下列程式碼。

Google::Ads::GoogleAds::Logging::GoogleAdsLogger::enable_all_logging();

如需其他選項,請參閱 Perl 程式庫記錄指南

curl

根據預設,curl 會將失敗的回應列印到 stderr

如何處理錯誤

如果發生錯誤,請按照下列步驟操作:

  1. 擷取例外狀況並擷取記錄檔:首先,請擷取例外狀況,並視需要擷取 API 記錄檔。
  2. 檢查 errors 清單:查看 GoogleAdsFailure 物件中的每個 GoogleAdsErrorerror_codemessage 會說明發生哪些錯誤。
  3. 檢查 locationlocation 欄位可協助您找出要求中發生問題的位置。
  4. 參閱說明文件:如要瞭解特定錯誤代碼,請查看常見錯誤頁面或完整的錯誤代碼參考資料,進一步瞭解錯誤和修正方法。
  5. 調整要求:根據錯誤訊息修正 API 要求。舉例來說,如果看到 REQUIRED_FIELD_MISSING,請務必在要求中提供該欄位。
  6. 記錄 request_id:如果無法解決錯誤,且需要聯絡支援團隊,請提供失敗要求的完整要求和回應記錄。請務必加入 request_id。Google 工程師可透過這個 ID 在 Google Ads API 伺服器記錄中找出失敗的要求詳細資料,並調查您的問題。

後續步驟

  • 請參閱「常見錯誤」,瞭解常見問題和解決方法。
  • 如要瞭解更進階的錯誤處理技術,包括重試邏輯和部分失敗,請參閱「瞭解 API 錯誤」。