根据response来判断错误,获取错误信息提示。
//@ts-check
/// <reference path="../types.d.ts" />
export const ERROR_NO_TOKEN_INFO = 10086;
export const ERROR_PASSWD_DIFF = 20488;
/**
* @param {{code: number, data: any}} response
*/
export function hasError(response) {
return response && response.code !== 200;
}
/**
* @param {'default'|'login'|'users'|'roles'|'license'|'upload'|'vendor'|'device'|'park'|'staff'|'dryrun'} category
* @param {{code: number, data: string}} response
*/
export function getErrorMessage(category, response) {
try {
return parse();
} catch (error) {
return `未知错误, 服务器返回: ${response.code} 处理异常: ${error.message || error}`;
}
function parse() {
if (!response) response = { code: 0, data: null };
const responseString =
typeof response.data === 'string' ? response.data : (JSON.stringify(response.data) || "");
const responseObject = parseResponse(responseString);
switch (category) {
case 'login': {
if (response.code === 401) return '用户账号或密码错误!';
break;
}
case 'users': {
// 用户管理等...
if (response.code === ERROR_PASSWD_DIFF) {
return '两次密码不相符!';
} else if (responseString.indexOf('still in use') > 0) {
return '当前角色仍在使用, 无法删除!';
} else if (response.code === 400 && responseString.indexOf('already exists') > 0) {
const mapper = {
username: "用户名已被占用",
email: "邮箱已被占用",
phone: "手机号已被占用",
empty: "条目已存在",
};
return mapper[getConflictField(responseString)];
}
break;
}
case 'roles': {
if (response.code === 400 && responseString.indexOf('already exists') > 0)
return '角色已存在!';
else if (response.code === 404)
return (typeof response.data === "string") ? response.data : "请求出错";
break;
}
case 'upload': {
if (response.code === 409) return '文件已存在, 请上传其他文件!';
break;
}
case 'license': {
return '生成授权信息出错!';
break;
}
case 'dryrun': {
if (responseString.indexOf('still in use') > 0) {
return '所选的试运行记录与点检任务已关联, 无法删除!';
} else if (responseString.indexOf("unresolved fault") > 0) {
return '该设备存在故障,无法开始试运行!';
}
break;
}
default: {
if (response.code === ERROR_PASSWD_DIFF) return '两次密码不相符!';
}
}
if (response.code === 403) return '暂无访问权限!';
if (response.code === 404) return '条目不存在!';
if (response.code === 409) return '条目已存在!';
if (response.code === 413) return '文件过大!';
if (response.code === 500) return '服务器内部错误';
return responseObject.message || '未知服务器错误';
}
}
function parseResponse(data) {
if (typeof data === 'object') return data;
if (typeof data !== 'string') return {};
try {
return JSON.parse(data);
} catch (error) {
return {};
}
}
function getConflictField(data) {
return /field":"(.*)"/.test(data) ? data.match(/field":"(.*)"/)[1] : "empty";
}
使用:
one rror(error) { this.setState({ error: getErrorMessage('default', error) }); }
one rrorInModal(error) { this.setState({ errorInModal: getErrorMessage('default', error) }); }