![](/img/trans.png)
[英]Is it ok to mix .catch() with async/await for error handling?
[英]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.