Geolocation capture error - Async Await

How can I catch a specific geolocation error to notify the user to enable geolocation?

The trap logs an error named PositionError as stated here in the Mozilla docs https://developer.mozilla.org/en-US/docs/Web/API/PositionError ".

* Note: my code doesn't catch the error, it just displays:

Uncaught (in promise) ReferenceError: PositionError is not defined

      

code

getCurrentLocation() {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        });
    });
},
async inout() {
    try {
        let location = await this.getCurrentLocation();
        let response = await axios.post(API.URL, {});
    } catch (e) {
        if(e instanceof PositionError) {
            console.log('position error')
        }
    }
}

      

+3


source to share


1 answer


The API getCurrentPosition()

was poorly designed with the expectation that users would immediately check for errors in the callback instead of passing them.

Since it PositionError

does not have a public constructor, it is window.PositionError

not defined.

As Fabian mentions in the comments, you can test the error like this:

if (e.toString() == '[object PositionError]') {
  console.log('position error')
}

      



or use a version of it if you're calling any API that might throw non-object errors (hopefully rare).

However, instead of cluttering your code, I recommend adding a better bug from your new async API instead getCurrentLocation()

(use fiddle to get around the SO snippet sandbox):

function getCurrentLocation(options) {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, ({code, message}) =>
      reject(Object.assign(new Error(message), {name: "PositionError", code})),
      options);
    });
};
async function inout() {
  try {
    console.log(await this.getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    }));
  } catch (e) {
    if (e.name == 'PositionError') {
      console.log(e.message + ". code = " + e.code);
    }
  }
}
inout().catch(e => console.log(e)); // User denied geolocation prompt. code = 1
      

Run codeHide result


+2


source







All Articles