エラー処理

このページでは、Maps JavaScript API と Place クラスを使用する際にエラーを処理する方法について説明します。

Google Maps JavaScript API では、エラーに次のクラスが使用されます。

  • MapsNetworkError は、ウェブサービスからのネットワーク エラーを表します(RPCStatus エラーを含む場合があります)。
  • MapsRequestError は、ウェブサービスからのリクエスト エラーを表します(HTTP の 4xx コードに相当)。
  • MapsServerError は、ウェブサービスからのサーバーサイド エラーを表します(HTTP の 5xx コードに相当します)。

MapsNetworkErrorMapsRequestErrorMapsServerError の各クラスは、マップのコアライブラリに属します。ライブラリの詳細を確認する。

これらの各クラスには、次のプロパティが含まれています。

code プロパティはエラーのタイプを示し、endpoint プロパティはエラーを返したエンドポイント(PLACES_DETAILS など)を示します。MapsNetworkErrorError のサブクラスであるため、namemessage などの他のプロパティも使用できます。

次のスニペットは、マップのエラー メッセージの構造を示しています。

  MapsRequestError: PLACES_GET_PLACE: INVALID_ARGUMENT: Error fetching fields: The provided Place ID: ChIJN5Nz71W3j4ARhx5bwpTQEGg**** is not valid.
  [error.name     ] [error.endpoint ] [error.code     ]
                    [error.message --->                ... ]
  

未加工のエラーには、エラー文字列のすべてが含まれます。error.message には、error.name を除くエラー文字列全体が含まれます。

次のスニペットは、Place クラスを使用する際のエラー処理を示しています。この例では、try/catch ブロックを使用して 3 つのエラータイプをそれぞれ処理しています。同様のコードを使用して、Maps JavaScript API の任意のクラスのエラーを処理できます。

async function getPlaceDetails() {
    const { Place } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    const { MapsNetworkError, MapsRequestError, MapsServerError } = await google.maps.importLibrary("core") as google.maps.CoreLibrary;

    // Use place ID to create a new Place instance.
    const place = new Place({
        id: 'ChIJN5Nz71W3j4ARhx5bwpTQEGg****', // Pass a bad Place ID to trigger an error.
    });

    // Error handling for fetchFields.
    try {
        // Call fetchFields, passing the desired data fields.
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
    } catch (error: any) {
        if (error && error instanceof google.maps.MapsRequestError) {
            // HTTP 4xx request error.
            console.error('fetchFields failed: MapsRequestError - check the request parameters', error);
        } else if (error && error instanceof google.maps.MapsServerError) {
            // HTTP 5xx server-side error.
            console.error('fetchFields failed: MapsServerError', error);
        } else if (error && error instanceof google.maps.MapsNetworkError) {
            // Network error.
            console.error('fetchFields failed: MapsNetworkError', error);
        }  else {
            console.error('fetchFields failed: An unknown error occurred', error);
        }
    }
    // ...
}