编程语言
首页 > 编程语言> > javascript – 捕获地理位置错误 – 异步等待

javascript – 捕获地理位置错误 – 异步等待

作者:互联网

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

catch记录了一个名为PositionError的错误,如Mozilla文档“https://developer.mozilla.org/en-US/docs/Web/API/PositionError”中所述.

*注意:我的代码没有捕获错误,它只显示:

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的设计很糟糕,假设用户会在回调中立即测试错误,而不是传递错误.

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

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

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

如果您正在调用任何可能导致非对象错误的API(希望很少见),请使用他的版本.

但是,我建议不要乱扔你的代码,而是从新的异步getCurrentLocation()API中抛出更好的错误(使用fiddle来绕过SO代码片段沙箱):

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

标签:javascript,geolocation,async-await,ecmascript-2017
来源: https://codeday.me/bug/20190522/1154066.html