api-failure-message.js
968 Bytes
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
/** 从 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
}