處理錯誤

本頁面說明如何在使用 Maps JavaScript API 和 Place 類別時處理錯誤。

Google Maps JavaScript API 使用下列類別處理錯誤:

MapsNetworkErrorMapsRequestErrorMapsServerError 類別屬於 Maps Core 程式庫。進一步瞭解程式庫

每個類別都包含下列屬性:

code 屬性會識別錯誤類型;endpoint 屬性則會識別傳回錯誤的端點 (例如 PLACES_DETAILS)。由於 MapsNetworkErrorError 的子類別,因此其他屬性 (包括 namemessage) 也適用。

以下程式碼片段顯示 Google 地圖錯誤訊息的結構:

  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 區塊處理三種錯誤類型。類似的程式碼可用於處理任何 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);
        }
    }
    // ...
}