uniapp 接口返回多项错误报错处理

js yekong 1799℃

数据格式

接口校验数据的时候,有时候会返回一组数据,这就需要遍历处理一下,然后返回其中一条错误。

errors: {,…}
DeductionRate: [,…]
DeliveryTimeout: [,…]
Price: ["Error converting value {null} to type 'System.Decimal'. Path 'Price', line 1, position 131."]
TakeMaximum: ["Error converting value {null} to type 'System.Int32'. Path 'TakeMaximum', line 1, position 187."]
status: 400
title: "One or more validation errors occurred."
traceId: "00-91e72f988ab446ea18e27ebe459922cd-490bba263a8170bd-00"

方法

接口封装判断,接口报400时,则获取错误字段,获取对应的错误内容,并显示。

if (response.statusCode == 400) {
			if (process.env.NODE_ENV === 'development') {
				console.log('开发环境')
				// console.log(response)
				// console.log(response.data)
				// console.log(response.data.errors)
				try {
					for (let i in response.data.errors) {
						if (response.data.errors[i][0]) {
							uni.showToast({
								title: response.data.errors[i][0],
								icon: 'none'
							});
							throw new Error("中断循环");
						}
					}
				} catch (e) {
					console.log(e)
				};
			} else {
				console.log('生产环境')
				uni.showToast({
					title: '异常错误',
					icon: 'none'
				});
			}
		}
喜欢 (0)