..._uniapp 统一处理错误返回">
当前位置:   article > 正文

uni-app接口统一处理request请求_uniapp 统一处理错误返回

uniapp 统一处理错误返回

用Promise就可以.then() 的方法进行回调
虽然有很多插件,但是这个是能看懂的
接下来是代码

新建一个request.js

import * as db from './db.js' //引入common
export const request = (params) => {
	uni.showLoading({
		title: "加载中"
	})
	return new Promise((resolve, reject) => {
		wx.request({
			...params,
			success(res) {
				var jsondata = res.data;
				if (jsondata.success) {
					resolve(jsondata);
				} else {
					showError(jsondata)
					resolve(jsondata);
					//应该是这个但它会抛异常统一处理后就不执行then事件了
					// reject(res.data)
				}
			},
			fail(err) {
				showError(err)
				reject(res.data)
			},
			complete() {
				uni.hideLoading();
			}
		})
	})
}
//错误处理
const showError = (error) => {
	var that = this
	if (error) {
		let data = error
		const token = db.get("userToken");
		console.log("------异常响应------", token)
		console.log("------异常响应------", error.status)
		switch (error.status) {
			case 403:
				uni.showToast({
					title: '拒绝访问',
					icon:'none',
					duration: 4000
				});
				break
			case 500:
				if (data.message == "Token失效,请重新登录") {
					uni.showModal({
						title: '登录已过期',
						content: '很抱歉,登录已过期,请重新登录',
						confirmText: '重新登录',
						success: function(res) {
							if (res.confirm) {
								db.del('userToken')
								//去我的页面登录
								uni.switchTab({
									url: '/pages/views/mine'
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					// update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
				}
				break
			case 404:
				uni.showToast({
					title: '很抱歉,资源未找到!',
					icon:'none',
					duration: 4000
				});
				break
			case 504:
				uni.showToast({
					title: '网络超时',
					icon:'none',
					duration: 2000
				});
				break
			case 502:
				uni.showToast({
					title: '服务器异常',
					icon:'none',
					duration: 2000
				});
				break
			case 401:
				uni.showToast({
					title: '未授权,请重新登录',
					icon:'none',
					duration: 4000
				});
				if (token=='') {
					setTimeout(() => {
						//去我的页面登录
						uni.switchTab({
							url: '/pages/views/mine'
						});
					}, 1500)
				}
				break
			default:
				uni.showToast({
					title: data.message,
					icon:'none',
					duration: 4000
				});
				break
		}
	}
	return null
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113

存token的本地存储类db.js

//取值
function get(key,sync = true) {
    try {
		if(sync){
			return uni.getStorageSync(key);
		}else{
			let data = '';
			uni.getStorage({
				key:key,
				success: function (res) {
					data = res.data;
				}
			});
			return data;
		}
    } catch (e) {
        return false;
    }
}

//赋值
function set(key, value, sync = true) {
    try {
        if (sync) {
            return uni.setStorageSync(key, value);
        } else {
            uni.setStorage({
                key: key,
                data: value
            });
        }
    } catch (e) {

    }
}

//移除
function del(key, sync = true){
    try {
        if (sync) {
            return uni.removeStorageSync(key);
        } else {
            uni.removeStorage({
                key: key
            });
        }
    } catch (e) {
        return false;
    }
}

//清空
function clear(sync = true){
    try {
        if (sync) {
            return uni.clearStorageSync();
        } else {
            uni.clearStorage();
        }
    } catch (e) {
        return false;
    }
}

export {
    get,
    set,
    del,
    clear
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

封装get,post 到request.js


import * as db from './db.js'
//后台路径
const apiBaseUrl = ''
import {request} from '@/config/request.js'
const post = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header);
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data: data,
		header:header,
		method: 'POST'
	});
}

const get = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header)
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data:data,
		header:header,
		method: 'GET'
	});
}
const setHeader = header => {
	let userToken = db.get("userToken");
	if (userToken) {
	  header[ 'X-Access-Token' ] = userToken // 让每个请求携带自定义 token 请根据实际情况自行修改
	}
	return header
}

//put
const put = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
	header=setHeader(header);
	
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data: data,
		header:header,
		method: 'PUT'
	});

}
// 普通上传图片
export const uploadImage = (num, callback) => {
	var header={
			'Accept': 'application/json',
			'Content-Type': 'multipart/form-data',
			// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header);
	uni.chooseImage({
		count: num,
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++) {
				uni.uploadFile({
					url: apiBaseUrl + '/web-api' +'/sys/common/upload',
					filePath: tempFilePaths[i],
					fileType: 'image',
					name: 'file',
					header: header,
					formData: {
						'method': 'images.upload',
						'upfile': tempFilePaths[i]
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						callback();
					},
					fail: (error) => {
						if (error && error.response) {
							showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					},
				});
			}
		}
	});
}


export {post,get}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114

api.js

import {get,post} from '@/config/config.js'
const randomImage = (params) => get('/sys/randomImage/'+params, null);
const extractRandom = (params)=>post("/iwrs/random/generate",params);
export {
  randomImage,
  extractRandom
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

调用

//mian.js
import * as Api from './api/api.js'
Vue.prototype.$api = Api;
//vue页面
this.$api.randomImage (param).then((res)=>{
				if(res.success){
					
				}else{
					
				}
			})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

附赠一个图片上传

ChooseImage() {
			var that = this;
			this.$config.uploadImage(5, res => {
				if (res.success) {
					if (!item.pics) {
						item.pics = [];
					}
					item.pics.push({
						src: res.data.url.replace(/\\/g, '/'),
						image_id: res.data.image_id
					});
					this.$set(this.form.items, index, item);
					that.$common.successToShow(res.msg);
				} else {
					that.$common.errorToShow(res.msg);
				}
			});
		},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/231234
推荐阅读
相关标签
  

闽ICP备14008679号