Rob*_*Rob 7 javascript geolocation async-await ecmascript-2017
如何捕获地理位置特定错误以通知用户他们必须打开地理位置?
catch记录了一个名为PositionError的错误,如Mozilla文档" https://developer.mozilla.org/en-US/docs/Web/API/PositionError "中所述.
*注意:我的代码没有捕获错误,它只显示:
Uncaught (in promise) ReferenceError: PositionError is not defined
Run Code Online (Sandbox Code Playgroud)
码
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')
}
}
}
Run Code Online (Sandbox Code Playgroud)
该getCurrentPosition()
API的设计很差,假设用户将在回调中立即测试错误,而不是将错误传递给用户。
由于PositionError
没有公共构造函数,window.PositionError
因此未定义。
正如Fabian在评论中提到的那样,您可以像这样测试错误:
if (e.toString() == '[object PositionError]') {
console.log('position error')
}
Run Code Online (Sandbox Code Playgroud)
或使用他的版本(如果您正在调用任何可能引发非对象错误的API(希望很少)。
但是,建议getCurrentLocation()
不要从新的异步API中抛出更好的错误(使用小提琴绕过SO代码段沙箱),而不是乱扔代码:
if (e.toString() == '[object PositionError]') {
console.log('position error')
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4028 次 |
最近记录: |