64 lines
2.1 KiB
JavaScript
64 lines
2.1 KiB
JavaScript
// 微信 BLE 常见 errCode 到可读文案映射。
|
||
const ERROR_MESSAGES = Object.freeze({
|
||
10000: '未初始化蓝牙适配器',
|
||
10001: '当前蓝牙适配器不可用',
|
||
10002: '没有找到指定设备',
|
||
10003: '连接失败',
|
||
10004: '没有找到指定服务',
|
||
10005: '没有找到指定特征值',
|
||
10006: '当前连接已断开',
|
||
10007: '当前特征值不支持此操作',
|
||
10008: '其余所有系统上报的异常',
|
||
10009: 'Android 系统特有,系统版本低于 4.3 不支持 BLE',
|
||
10010: '已连接',
|
||
10011: '配对设备需要配对码',
|
||
10012: '连接超时',
|
||
10013: '连接 deviceId 为空或者是格式不正确',
|
||
10014: 'writeCharacteristicValue: 找不到指定设备',
|
||
10015: 'readCharacteristicValue: 找不到指定设备',
|
||
10016: 'openBluetoothAdapter: 未找到蓝牙适配器',
|
||
10017: 'startBluetoothDevicesDiscovery: 未找到蓝牙适配器',
|
||
10018: 'stopBluetoothDevicesDiscovery: 调用失败',
|
||
10019: 'getBluetoothDevices: 调用失败',
|
||
10020: 'getConnectedBluetoothDevices: 调用失败'
|
||
})
|
||
|
||
/**
|
||
* 构造统一 BLE Error,方便上层直接读取 code/message。
|
||
*/
|
||
export function createBleError(code, message, payload = {}) {
|
||
const err = new Error(message || ERROR_MESSAGES[code] || '蓝牙操作失败')
|
||
err.name = 'BleError'
|
||
err.code = code
|
||
Object.assign(err, payload)
|
||
return err
|
||
}
|
||
|
||
/**
|
||
* 归一化任意错误对象(uni err / 原生 Error / 空值)。
|
||
*/
|
||
export function normalizeBleError(error, fallbackMessage = '蓝牙操作失败') {
|
||
if (!error) {
|
||
return createBleError(-1, fallbackMessage)
|
||
}
|
||
|
||
if (error.name === 'BleError') {
|
||
return error
|
||
}
|
||
|
||
const errCode = typeof error.errCode === 'number' ? error.errCode : -1
|
||
const message = error.errMsg || ERROR_MESSAGES[errCode] || fallbackMessage
|
||
return createBleError(errCode, message, { raw: error })
|
||
}
|
||
|
||
/**
|
||
* 安全获取错误文案,避免页面层处理 null/undefined 分支。
|
||
*/
|
||
export function getBleErrorText(error, fallbackText = '蓝牙操作失败') {
|
||
if (!error) {
|
||
return fallbackText
|
||
}
|
||
|
||
return error.message || ERROR_MESSAGES[error.code] || fallbackText
|
||
}
|