fix:修改客服报错问题
This commit is contained in:
@@ -2,6 +2,7 @@
|
|||||||
import { onLaunch, onShow } from '@dcloudio/uni-app'
|
import { onLaunch, onShow } from '@dcloudio/uni-app'
|
||||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { getStoredToken } from '@/utils/auth-token'
|
||||||
|
import { installLocalizedToast } from '@/utils/localized-toast'
|
||||||
import { staticAssets } from '@/utils/static-assets'
|
import { staticAssets } from '@/utils/static-assets'
|
||||||
|
|
||||||
const HOME_ROUTE = '/pages/device/index'
|
const HOME_ROUTE = '/pages/device/index'
|
||||||
@@ -32,6 +33,7 @@ function bootstrapAuthRoute() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onLaunch(() => {
|
onLaunch(() => {
|
||||||
|
installLocalizedToast()
|
||||||
applyH5Favicon()
|
applyH5Favicon()
|
||||||
bootstrapAuthRoute()
|
bootstrapAuthRoute()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -152,17 +152,36 @@ function resolveUploadUrl(url: string): string {
|
|||||||
return `${getApiBaseUrl()}${path}`
|
return `${getApiBaseUrl()}${path}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const UPLOAD_NETWORK_ERROR = '网络异常,请检查网络后重试'
|
||||||
|
|
||||||
|
function isUploadTransportError(rawData: string, errMsg?: string): boolean {
|
||||||
|
const payload = `${errMsg || ''} ${rawData}`.trim()
|
||||||
|
if (!payload) return false
|
||||||
|
return /uploadFile:fail|downloadFile:fail|request:fail|statusCode:\s*null/i.test(payload)
|
||||||
|
}
|
||||||
|
|
||||||
function handleUploadSuccess<T>(
|
function handleUploadSuccess<T>(
|
||||||
statusCode: number,
|
statusCode: number | undefined,
|
||||||
rawData: string,
|
rawData: string,
|
||||||
resolve: (value: T) => void,
|
resolve: (value: T) => void,
|
||||||
reject: (reason: ApiError) => void,
|
reject: (reason: ApiError) => void,
|
||||||
|
errMsg?: string,
|
||||||
) {
|
) {
|
||||||
if (statusCode < 200 || statusCode >= 300) {
|
if (isUploadTransportError(rawData, errMsg)) {
|
||||||
let message = `上传失败(${statusCode})`
|
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusCode == null || statusCode < 200 || statusCode >= 300) {
|
||||||
|
let message = statusCode == null
|
||||||
|
? UPLOAD_NETWORK_ERROR
|
||||||
|
: `上传失败(${statusCode})`
|
||||||
try {
|
try {
|
||||||
const body = JSON.parse(rawData) as ApiResponse
|
const body = JSON.parse(rawData) as ApiResponse
|
||||||
message = body.msg || body.message || message
|
const apiMessage = body.msg || body.message
|
||||||
|
if (apiMessage && !/^[a-z0-9_.\-:()\s]+$/i.test(apiMessage)) {
|
||||||
|
message = apiMessage
|
||||||
|
}
|
||||||
reject(new ApiError(message, body.code ?? statusCode))
|
reject(new ApiError(message, body.code ?? statusCode))
|
||||||
return
|
return
|
||||||
} catch {
|
} catch {
|
||||||
@@ -182,7 +201,12 @@ function handleUploadSuccess<T>(
|
|||||||
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
resolve(unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>))
|
const data = unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>)
|
||||||
|
if (data == null || (typeof data === 'object' && !Object.keys(data as object).length)) {
|
||||||
|
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resolve(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
function uploadViaUniMultipart<T>(
|
function uploadViaUniMultipart<T>(
|
||||||
@@ -198,37 +222,85 @@ function uploadViaUniMultipart<T>(
|
|||||||
name: fieldName,
|
name: fieldName,
|
||||||
header: resolveUploadAuthHeaders(authMode),
|
header: resolveUploadAuthHeaders(authMode),
|
||||||
success: (res) => {
|
success: (res) => {
|
||||||
handleUploadSuccess<T>(res.statusCode, String(res.data ?? ''), resolve, reject)
|
handleUploadSuccess<T>(
|
||||||
|
res.statusCode,
|
||||||
|
String(res.data ?? ''),
|
||||||
|
resolve,
|
||||||
|
reject,
|
||||||
|
res.errMsg,
|
||||||
|
)
|
||||||
},
|
},
|
||||||
fail: (err) => {
|
fail: (err) => {
|
||||||
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, '上传失败')))
|
reject(new ApiError(normalizeNetworkErrorMessage(err.errMsg, UPLOAD_NETWORK_ERROR)))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** H5 用 fetch 发送 multipart,确保 Authorization: Bearer xxx 能带上 */
|
/** H5 用 fetch 发送 multipart,确保 Authorization: Bearer xxx 能带上 */
|
||||||
|
/** App 端用 plus.uploader,避免 uni.uploadFile 失败时框架自动弹英文 toast */
|
||||||
|
function uploadViaPlusUploader<T>(
|
||||||
|
targetUrl: string,
|
||||||
|
filePath: string,
|
||||||
|
fieldName: string,
|
||||||
|
authMode: UploadAuthMode,
|
||||||
|
): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (typeof plus === 'undefined' || typeof plus.uploader?.createUpload !== 'function') {
|
||||||
|
uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode).then(resolve).catch(reject)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = plus.uploader.createUpload(
|
||||||
|
targetUrl,
|
||||||
|
{ method: 'POST' },
|
||||||
|
(upload, status) => {
|
||||||
|
const rawData = upload.responseText || ''
|
||||||
|
if (status == null || status < 0) {
|
||||||
|
reject(new ApiError(UPLOAD_NETWORK_ERROR))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
handleUploadSuccess<T>(status, rawData, resolve, reject)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const headers = authMode === 'cs'
|
||||||
|
? buildCsUploadAuthHeaders()
|
||||||
|
: buildUploadAuthHeaders()
|
||||||
|
Object.entries(headers).forEach(([key, value]) => {
|
||||||
|
task.setRequestHeader(key, value)
|
||||||
|
})
|
||||||
|
task.addFile(filePath, { key: fieldName })
|
||||||
|
task.start()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
async function uploadViaFetchH5<T>(
|
async function uploadViaFetchH5<T>(
|
||||||
targetUrl: string,
|
targetUrl: string,
|
||||||
filePath: string,
|
filePath: string,
|
||||||
fieldName: string,
|
fieldName: string,
|
||||||
authMode: UploadAuthMode,
|
authMode: UploadAuthMode,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
const blobRes = await fetch(filePath)
|
try {
|
||||||
const blob = await blobRes.blob()
|
const blobRes = await fetch(filePath)
|
||||||
const ext = blob.type.split('/')[1] || 'jpg'
|
const blob = await blobRes.blob()
|
||||||
const formData = new FormData()
|
const ext = blob.type.split('/')[1] || 'jpg'
|
||||||
formData.append(fieldName, blob, `upload.${ext}`)
|
const formData = new FormData()
|
||||||
|
formData.append(fieldName, blob, `upload.${ext}`)
|
||||||
|
|
||||||
const response = await fetch(targetUrl, {
|
const response = await fetch(targetUrl, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: resolveUploadAuthHeaders(authMode),
|
headers: resolveUploadAuthHeaders(authMode),
|
||||||
body: formData,
|
body: formData,
|
||||||
})
|
})
|
||||||
const rawData = await response.text()
|
const rawData = await response.text()
|
||||||
return new Promise<T>((resolve, reject) => {
|
return await new Promise<T>((resolve, reject) => {
|
||||||
handleUploadSuccess<T>(response.status, rawData, resolve, reject)
|
handleUploadSuccess<T>(response.status, rawData, resolve, reject)
|
||||||
})
|
})
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err)
|
||||||
|
throw new ApiError(normalizeNetworkErrorMessage(message, UPLOAD_NETWORK_ERROR))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runUpload<T>(
|
async function runUpload<T>(
|
||||||
@@ -241,6 +313,10 @@ async function runUpload<T>(
|
|||||||
return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode)
|
return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode)
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef APP-PLUS
|
||||||
|
return uploadViaPlusUploader<T>(targetUrl, filePath, fieldName, authMode)
|
||||||
|
// #endif
|
||||||
|
|
||||||
return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode)
|
return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { createSSRApp } from "vue";
|
import { createSSRApp } from "vue";
|
||||||
import App from "./App.vue";
|
import App from "./App.vue";
|
||||||
import { registerGlobalComponents } from "./plugins/register-global-components";
|
import { registerGlobalComponents } from "./plugins/register-global-components";
|
||||||
|
import { installLocalizedToast } from "./utils/localized-toast";
|
||||||
|
|
||||||
|
installLocalizedToast();
|
||||||
|
|
||||||
export function createApp() {
|
export function createApp() {
|
||||||
const app = createSSRApp(App);
|
const app = createSSRApp(App);
|
||||||
|
|||||||
@@ -559,8 +559,8 @@ export function useSupport() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
await sendUserImageMessage(ossId, previewUrl)
|
await sendUserImageMessage(ossId, previewUrl)
|
||||||
} catch (err) {
|
} catch {
|
||||||
uni.showToast({ title: getErrorMessage(err, '图片上传失败'), icon: 'none' })
|
uni.showToast({ title: '网络异常,请检查网络后重试', icon: 'none' })
|
||||||
} finally {
|
} finally {
|
||||||
uni.hideLoading()
|
uni.hideLoading()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,9 +22,42 @@ export function unwrapApiData<T>(body: ApiResponse<T> & Record<string, unknown>)
|
|||||||
return body as T
|
return body as T
|
||||||
}
|
}
|
||||||
|
|
||||||
const NETWORK_ERROR_PATTERN = /request:fail|network\s*error|unable to resolve host|no address associated|failed to connect|connection\s*(refused|reset|timed out|timeout)|timed?\s*out|offline|statuscode:\s*-1|err_connection|net::/i
|
const NETWORK_ERROR_PATTERN = /request:fail|uploadFile:fail|downloadFile:fail|chooseImage:fail|connectSocket:fail|network\s*error|network\s*request\s*failed|failed\s+to\s+fetch|fetch\s+failed|load\s+failed|unable to resolve host|no address associated|failed to connect|connection\s*(refused|reset|timed out|timeout)|timed?\s*out|offline|statuscode:\s*(null|-1)|err_connection|net::|the internet connection appears to be/i
|
||||||
|
|
||||||
/** 将 uni.request / 系统层英文网络错误转为中文提示 */
|
const UNI_API_FAIL_PATTERN = /(request|uploadFile|downloadFile|chooseImage|connectSocket):fail\b/i
|
||||||
|
|
||||||
|
function hasChinese(text: string): boolean {
|
||||||
|
return /[\u4e00-\u9fff]/.test(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isEnglishSystemError(text: string): boolean {
|
||||||
|
const value = text.trim()
|
||||||
|
if (!value) return true
|
||||||
|
if (hasChinese(value)) return false
|
||||||
|
return /[a-z]/i.test(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectErrorTexts(err: unknown): string[] {
|
||||||
|
const texts: string[] = []
|
||||||
|
if (typeof err === 'string') {
|
||||||
|
texts.push(err)
|
||||||
|
return texts
|
||||||
|
}
|
||||||
|
if (!err || typeof err !== 'object') return texts
|
||||||
|
|
||||||
|
const record = err as Record<string, unknown>
|
||||||
|
if (typeof record.message === 'string') texts.push(record.message)
|
||||||
|
if (typeof record.errMsg === 'string') texts.push(record.errMsg)
|
||||||
|
if (typeof record.msg === 'string') texts.push(record.msg)
|
||||||
|
|
||||||
|
if (err instanceof Error && err.message) {
|
||||||
|
texts.push(err.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...new Set(texts.filter(Boolean))]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将 uni.request / uploadFile / fetch 等系统层英文网络错误转为中文提示 */
|
||||||
export function normalizeNetworkErrorMessage(
|
export function normalizeNetworkErrorMessage(
|
||||||
message?: string,
|
message?: string,
|
||||||
fallback = '网络异常,请检查网络后重试',
|
fallback = '网络异常,请检查网络后重试',
|
||||||
@@ -32,24 +65,32 @@ export function normalizeNetworkErrorMessage(
|
|||||||
const text = message?.trim() ?? ''
|
const text = message?.trim() ?? ''
|
||||||
if (!text) return fallback
|
if (!text) return fallback
|
||||||
if (NETWORK_ERROR_PATTERN.test(text)) return fallback
|
if (NETWORK_ERROR_PATTERN.test(text)) return fallback
|
||||||
|
if (UNI_API_FAIL_PATTERN.test(text)) return fallback
|
||||||
|
if (isEnglishSystemError(text) && /fail|error|timeout|network|statuscode|upload|request|socket|fetch|offline|null/i.test(text)) {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getErrorMessage(err: unknown, fallback = '请求失败'): string {
|
export function getErrorMessage(err: unknown, fallback = '请求失败'): string {
|
||||||
if (err instanceof ApiError) {
|
const texts = collectErrorTexts(err)
|
||||||
return normalizeNetworkErrorMessage(err.message, fallback)
|
|
||||||
}
|
for (const text of texts) {
|
||||||
if (err instanceof Error && err.message) {
|
const normalized = normalizeNetworkErrorMessage(text, fallback)
|
||||||
return normalizeNetworkErrorMessage(err.message, fallback)
|
if (normalized !== text) return normalized
|
||||||
}
|
if (!isEnglishSystemError(text)) return text
|
||||||
if (err && typeof err === 'object' && 'errMsg' in err) {
|
|
||||||
const errMsg = String((err as { errMsg?: string }).errMsg || '')
|
|
||||||
if (errMsg) return normalizeNetworkErrorMessage(errMsg, fallback)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (err && typeof err === 'object' && 'data' in err) {
|
if (err && typeof err === 'object' && 'data' in err) {
|
||||||
const data = (err as { data?: ApiResponse }).data
|
const data = (err as { data?: ApiResponse }).data
|
||||||
if (data?.msg) return data.msg
|
if (data?.msg && !isEnglishSystemError(data.msg)) return data.msg
|
||||||
if (data?.message) return data.message
|
if (data?.message && !isEnglishSystemError(data.message)) return data.message
|
||||||
}
|
}
|
||||||
|
|
||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 文件上传失败提示(无网 / 系统层错误统一中文) */
|
||||||
|
export function getUploadErrorMessage(err: unknown): string {
|
||||||
|
return getErrorMessage(err, '网络异常,请检查网络后重试')
|
||||||
|
}
|
||||||
|
|||||||
47
src/utils/localized-toast.ts
Normal file
47
src/utils/localized-toast.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { normalizeNetworkErrorMessage } from '@/utils/api-error'
|
||||||
|
|
||||||
|
const NETWORK_TOAST = '网络异常,请检查网络后重试'
|
||||||
|
|
||||||
|
function localizeToastTitle(title: unknown): string {
|
||||||
|
return normalizeNetworkErrorMessage(String(title ?? ''), NETWORK_TOAST)
|
||||||
|
}
|
||||||
|
|
||||||
|
function patchUniShowToast() {
|
||||||
|
if (typeof uni === 'undefined' || typeof uni.showToast !== 'function') return
|
||||||
|
const marker = '__localizedToastPatched__'
|
||||||
|
if ((uni.showToast as { [marker]?: boolean })[marker]) return
|
||||||
|
|
||||||
|
const raw = uni.showToast.bind(uni)
|
||||||
|
const patched = (options: string | UniApp.ShowToastOptions) => {
|
||||||
|
if (typeof options === 'string') {
|
||||||
|
return raw({ title: localizeToastTitle(options), icon: 'none' })
|
||||||
|
}
|
||||||
|
return raw({
|
||||||
|
...options,
|
||||||
|
title: localizeToastTitle(options?.title),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
;(patched as { [marker]?: boolean })[marker] = true
|
||||||
|
uni.showToast = patched as typeof uni.showToast
|
||||||
|
}
|
||||||
|
|
||||||
|
function patchNativeToast() {
|
||||||
|
// #ifdef APP-PLUS
|
||||||
|
if (typeof plus === 'undefined') return
|
||||||
|
const nativeUI = plus.nativeUI as {
|
||||||
|
toast?: (message: string, styles?: unknown) => void
|
||||||
|
__localizedToastPatched__?: boolean
|
||||||
|
}
|
||||||
|
if (!nativeUI?.toast || nativeUI.__localizedToastPatched__) return
|
||||||
|
|
||||||
|
const raw = nativeUI.toast.bind(nativeUI)
|
||||||
|
nativeUI.toast = (message: string, styles?: unknown) => raw(localizeToastTitle(message), styles)
|
||||||
|
nativeUI.__localizedToastPatched__ = true
|
||||||
|
// #endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 启动时安装,拦截框架自动弹出的英文 uploadFile/request 错误 */
|
||||||
|
export function installLocalizedToast() {
|
||||||
|
patchUniShowToast()
|
||||||
|
patchNativeToast()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user