gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:42 27 4
gpt4 key购买 nike

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

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 没有公共(public)构造函数,因此未定义 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 - 捕获地理位置错误 - 异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427908/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com