[英]Warning: a promise was rejected with a non-error: [object GeolocationPositionError]
在尝试从用户的浏览器获取地理位置时,如果用户拒绝许可或阻止浏览器共享位置,我们会收到来自 Bluebird 的控制台警告,上面写着: Warning: a promise was rejected with a non-error: [object GeolocationPositionError]
。
但是,当我们捕获并记录错误时,我们会收到错误消息:来自 Geolocation API 的GeolocationPositionError的User denied geolocation prompt
。 我想对于将返回 GeolocationPositionError 的其他两种情况(内部 position 错误或超时),将记录相同的警告。
那么为什么我们会收到控制台警告以及我们如何正确处理它呢?
这是处理浏览器导航器和地理位置的代码:
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'));
}
});
}
阅读 Bluebird 关于其警告消息的文档: “警告:promise 因非错误被拒绝” ,我发现问题在于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'));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.