api-failure-message.js 968 Bytes
/** 从 API 响应或异常中解析用户可读失败文案(优先后端 message) */
function pickNonEmptyString(value) {
	if (value == null) {
		return ''
	}
	const text = String(value).trim()
	if (!text || text === 'ok') {
		return ''
	}
	return text
}

function resolveApiFailureMessage(res, error, fallback = '提交失败') {
	if (res) {
		const message = pickNonEmptyString(res.message || res.msg)
		if (message) {
			return message
		}
		const subErrors = res.subErrors
		if (Array.isArray(subErrors) && subErrors.length) {
			const first = subErrors[0]
			const subMessage =
				typeof first === 'string'
					? first
					: first?.message || first?.msg || first?.errorMessage
			const normalized = pickNonEmptyString(subMessage)
			if (normalized) {
				return normalized
			}
		}
	}
	const errorMessage = pickNonEmptyString(error?.message)
	if (errorMessage) {
		return errorMessage
	}
	return fallback
}

module.exports = {
	resolveApiFailureMessage
}