Search code examples
javascriptbrowsergeolocationbluebirdnavigator

Warning: a promise was rejected with a non-error: [object GeolocationPositionError]


While trying to get the geolocation from the user's browser, if the user has denied permission or blocked the browser from sharing the location we get a console warning from Bluebird that says: Warning: a promise was rejected with a non-error: [object GeolocationPositionError].

However when we catch and log the error, we get the error message: User denied geolocation prompt which comes from the Geolocation API's GeolocationPositionError. I imagine the same warning would be logged for the other two cases in which the GeolocationPositionError would be returned (an internal position error or a timeout).

So why are we getting that console warning and how do we handle it properly?

Here is the code that handles the browser navigator & geolocation:

import Promise from 'bluebird';

function getUserLocation() {
  return new Promise(function(resolve, reject) {
    if (navigator && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    } else {
      // Browser does not support geolocation at all
      reject(new Error('Geolocation is unsupported'));
    }
  });
}

Solution

  • Reading Bluebird's documentation on its warning message: "Warning: a promise was rejected with a non-error", I found that the problem was that the GeolocationPositionError is not a Javascript Error instance which is explicitly what Bluebird is expecting. So instead, customizing the reject() callback to explicitly cast the GeolocationPositionError as an Error resolved the console warning and error handling, for any case of the GeolocationPositionError.

    import Promise from 'bluebird';
    
    export function getUserLocation() {
      return new Promise(function(resolve, reject) {
        if (navigator && navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            resolve,
            (geolocationPositionError) => { // reject
              // Note: must explicitly cast the `GeolocationPositionError` as an Error instance since bluebird explicitly expects a javascript Error object
              // see http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-rejected-with-a-non-error
              // and `GeolocationPositionError` is not an Error instance, see https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError
              return reject(new Error(geolocationPositionError));
            }
          );
        } else {
          // Browser does not support geolocation at all
          reject(new Error('Geolocation is unsupported'));
        }
      });