Error Handling

When making requests to the Geocoding API, it's important to keep in mind that a request may not always be successful.

Should the Geocoding API respond with an error, the Skybrud.Social.Google.Geocoding package will throw an exception of the type GeocodingHttpException.

As an example, the snippet below will try to lookup a place using an invalid ID:

@using Skybrud.Social.Google.Geocoding
@using Skybrud.Social.Google.Geocoding.Exceptions
@using Skybrud.Social.Google.Geocoding.Models
@using Skybrud.Social.Google.Geocoding.Responses
@inherits Microsoft.AspNetCore.Mvc.Razor.RazorPage<Skybrud.Social.Google.GoogleHttpService>

@{

    try {

        // Make the request to the Geocoding API
        GeocodingResultListResponse response = await Model
            .Geocoding()
            .GetPlaceAsync("hello there");

        // Iterate through the result
        foreach (GeocodingResult result in response.Body.Results) {

            <p>
                <strong>@result.PlaceId</strong><br/>
                @result.FormattedAddress <small>(@string.Join(", ", result.Types))</small>
            </p>

        }

        <pre>@response.StatusCode</pre>
        <pre>@response.ResponseUri</pre>
        <pre>@response.Body.JObject</pre>

    } catch (GeocodingHttpException ex) {

        <pre>@ex.Message</pre>

        <pre>@ex.StatusCode</pre>

        <pre>@ex.Response.Body</pre>

    } catch (Exception ex) {

        <pre>@ex.Message</pre>

    }

}

In the case with an invalid ID, the Geocoding API will respond with a 400 Bad Request status code, and the following JSON response body:

{
   "error_message" : "Invalid request. Invalid 'place_id' parameter.",
   "results" : [],
   "status" : "INVALID_REQUEST"
}

The status code will be available via the GeocodingHttpException instance's StatusCode property, and the error_message will be available via the Message property.

A request to the Geocoding API may however also fail for other reasons - e.g. network connectivity issues if the Geocoding API is down, or you're experiencecing network connectivty issues in general. This won't be caught by the GeocodingHttpException class, so it's recommended to have a final catch for the standard Exception class.