在进行网络请求时,除了正常能接收到响应时,也会存在一些特殊情况和异常情形。此时就需要对网络请求进行严格和兜底处理,避免给用户造成不好的体验。
先来看示例代码:
uni.showLoading()
const pets = ref([])
function getPets(){
uni.request({
url:"https://tea.qingnian8.com/tools/petShow",
data:{size:10},
header:{"access-key":428771}
}).then(res=>{
if(res.data.errCode === 0){
console.log(res)
pets.value = res.data.data
}else if(res.data.errCode === 400){
uni.showToast({
title:res.data.errMsg,
icon:"none",
duration:2000
})
}
}).catch(err=>{
uni.showToast({
title:"请求方式有误,请检查纠正后重试",
icon:"none"
})
}).finally(()=>{
console.log(123)
uni.hideLoading()
})
}
上面的代码实现当后台返回的响应状态为0时,即正常返回时才进行赋值,同时使用catch将一些异常情况展示出来,方便用户识别,最后使用finally进行兜底处理,无论请求成功还是失败,都要执行的操作。