uniCloud 统一拦截器使用

本文介绍了如何在uniCloud中使用uni.addInterceptor来统一处理错误,特别是在配合uni-id进行用户注册逻辑时,通过在main.js设置拦截器,对'callFunction'的返回结果进行检查,如果errCode不为0,则抛出错误。这提供了一种全局错误处理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档:

uni.addInterceptor(STRING, OBJECT)

添加拦截器

STRING 参数说明

需要拦截的api名称,如:uni.addInterceptor('request', OBJECT) ,将拦截 uni.request()

OBJECT 参数说明

参数名类型必填默认值说明平台差异说明
invokeFunction拦截前触发
successFunction成功回调拦截
failFunction失败回调拦截
completeFunction完成回调拦截

需要在main.js里添加一下代码

// 统一的错误拦截
uniCloud.addInterceptor('callFunction',{
    success(res){
        const {result}=res
        if(result.errCode!==0){
            throw new Error(result.errMsg)
        }
    }
})

具体业务代码:(uniCloud配合uni-id用户注册逻辑)

async register() {
					try{
						uni.showLoading({
							title:"注册中"
						})
						console.log('111'+this.avatar.url)
						const forms = await this.$refs.forms.validate()
						const res=await uniCloud.callFunction({
							name:"index",
							data:{
								...forms,
								avatar: this.avatar.url
							}
						})
							uni.showToast({
								title:"注册成功",
								icon:'none'
							})
						console.log(res.result.code)
						console.log(res)
					}catch(e){ 
						uni.showToast({
							title: e.message || '校验失败',
							icon: 'none'
						})
					}finally{
						uni.hideLoading()
					}	
				}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值