警告:承诺以非错误被拒绝:[object GeolocationPositionError]

问题描述 投票:0回答:1

[尝试从用户的浏览器获取地理位置时,如果用户拒绝了许可或阻止了浏览器共享位置,我们会从Bluebird收到控制台警告,内容为:Warning: a promise was rejected with a non-error: [object GeolocationPositionError]

但是,当我们捕获并记录错误时,会收到错误消息:User denied geolocation prompt,它来自地理位置API的GeolocationPositionError。我想象在其他两种情况下将返回GeolocationPositionError(内部位置错误或超时)的情况下,将记录相同的警告。

那么为什么我们会收到该控制台警告,以及如何正确处理它?

这里是处理浏览器导航器和地理位置的代码:

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'));
    }
  });
}
javascript browser geolocation bluebird navigator
1个回答
0
投票

阅读有关警告消息的Bluebird文档:"Warning: a promise was rejected with a non-error",我发现问题是GeolocationPositionError不是Javascript Error实例,这显然是Bluebird所期望的。因此,相反,自定义reject()回调以将GeolocationPositionError显式转换为Error可以解决对于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'));
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.