繁体   English   中英

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

[英]Catch Geolocation Error - Async Await

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

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中抛出一个更好的错误(使用小提琴绕过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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM