Google Ads API에 요청을 전송할 때 다양한 이유로 실패할 수 있습니다. 예를 들어 잘못된 인수를 제공하거나 계정에서 새 캠페인 생성 한도에 도달했을 수 있습니다. 이 경우 API는 무엇이 잘못되었는지 알리는 오류를 반환합니다.
이 가이드에서는 더 강력한 애플리케이션을 빌드할 수 있도록 API 오류를 읽고 처리하는 방법을 설명합니다.
오류 구조
Google의 클라이언트 라이브러리 중 하나를 사용하는 경우 API 오류가 예외로 표시됩니다. 이러한 예외에는 오류가 발생한 이유를 파악하는 데 도움이 되는 세부정보가 포함되어 있습니다.
Google Ads API는 표준 형식으로 오류 정보를 반환합니다. 오류가 발생하면 응답에 GoogleAdsFailure 객체가 포함됩니다. 이 객체에는 개별 GoogleAdsError 객체 목록이 포함되어 있으며 각 객체는 특정 오류를 자세히 설명합니다.
각 GoogleAdsError 객체는 다음을 제공합니다.
error_code: 오류 유형을 알려주는 특정 오류 코드입니다(예:AuthenticationError.NOT_ADS_USER).message: 오류가 발생한 이유에 대해 사람이 읽을 수 있는 설명입니다.trigger: 오류를 일으킨 값입니다(예: '1234').location: 요청의 어느 부분이 오류를 일으켰는지에 관한 세부정보입니다(예: 특정 필드 이름).
오류 목록 외에도 GoogleAdsFailure에는 오류가 발생한 API 요청의 고유 식별자인 requestId이 포함됩니다.
오류 예시
다음은 JSON 형식의 오류 예시입니다. 이 오류는 색인 0의 ad_group에 있는 name 필드가 요청에서 누락되었음을 나타냅니다.
{
"code": 3,
"message": "Request contains an invalid argument.",
"details": [
{
"@type": "type.googleapis.com/google.ads.googleads.v25.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 오류에 대해 자세히 알아보려면 API 오류 이해하기를 참고하세요.
클라이언트 라이브러리 예
다음 섹션에서는 다양한 클라이언트 라이브러리에서 오류를 처리하는 방법을 보여줍니다.
자바
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
);
$errors = $googleAdsException->getGoogleAdsFailure()->getErrors();
foreach ($errors 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 "
f"'{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 클라이언트 라이브러리 로깅 가이드를 참고하세요.
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에 출력합니다.
오류 처리 방법
오류가 발생하면 다음 단계를 따르세요.
- 예외 포착 및 로그 캡처: 예외를 포착하고 선택적으로 API 로그를 캡처합니다.
errors목록 검사:GoogleAdsFailure객체에서 각GoogleAdsError을 살펴봅니다.error_code및message은 무엇이 잘못되었는지 알려줍니다.location값 확인:location필드를 사용하면 요청에서 문제가 발생한 위치를 정확히 파악할 수 있습니다.- 문서 참고: 특정 오류 코드의 경우 일반적인 오류 페이지 또는 전체 오류 코드 참조에서 오류 및 수정 방법에 관한 자세한 내용을 확인하세요.
- 요청 조정: 오류 메시지에 따라 API 요청을 수정합니다. 예를 들어
REQUIRED_FIELD_MISSING가 표시되면 요청에 해당 필드를 제공해야 합니다. request_id로깅: 오류 해결 방법을 알 수 없어 지원팀에 문의해야 하는 경우 실패한 요청의 전체 요청 및 응답 로그를 포함하세요.request_id을 포함해야 합니다. 이 ID는 Google 엔지니어가 Google Ads API 서버 로그에서 실패한 요청 세부정보를 찾아 문제를 조사하는 데 도움이 됩니다.