捕获地理位置错误 - 异步等待 [英] Catch Geolocation Error - Async Await

查看:71
本文介绍了捕获地理位置错误 - 异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何捕获地理位置特定错误以通知用户他们必须打开地理位置?

How can I catch the geolocation specific error to notify the user that they must have geolocation turned on?

catch会在Mozilla文档 PositionError 的错误。 org / en-US / docs / Web / API / PositionErrorrel =nofollow noreferrer> https://developer.mozilla.org/en-US/docs/Web/API/PositionError

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

*注意:我的代码没有发现错误,只显示:

*Note: my code does not catch the error, it simply displays:

Uncaught (in promise) ReferenceError: PositionError is not defined

代码

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')
        }
    }
}


推荐答案

getCurrentPosition() API的设计很糟糕,假设用户会在回调中立即测试错误,而不是传递它们。

The getCurrentPosition() API was poorly designed, assuming users would test errors immediately in the callback, instead of passing them up.

由于 PositionError 没有公共构造函数, window.PositionError 未定义。

Since PositionError has no public constructor, window.PositionError is not defined.

正如Fabian所提到的那样评论,你可以测试这样的错误:

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

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

或如果你正在调用任何可能引发非对象错误的API(希望很少见),请使用他的版本。

or use his version if you're calling any API likely to throw non-object errors (hopefully rare).

但是,我建议抛弃更好的代码而不是乱扔垃圾代码来自新异步的错误 getCurrentLocation() A. PI代替(使用小提琴来绕过SO代码片段沙箱):

However, instead of littering your code, I recommend throwing a better error from your new async getCurrentLocation() API instead (use fiddle to get around SO code 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

这篇关于捕获地理位置错误 - 异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆