4.2.6 框架之网络请求-拦截器

在整个http的链路中,异常错误对前端来说尤为重要,他作用在很多不同的场景,通用的比如500, 502等; 一个好的软件通常需要在不同的错误场景中做不同的事情。当用户cookie失效时,希望能自动跳转到登录页;当用户权限发生变更时,希望能跳转到一个友好的提示页;那么如何满足这些个性化的诉求呢?接下来让我们一起了解oinone前端网络请求-拦截器。

一、入口

在src目录下main.ts中可以看到VueOioProvider,这是系统功能提供者的注册入口

image.png

图4-2-6-1 VueOioProvider

import interceptor from './middleware/network-interceptor';
VueOioProvider(
  {
    http: {
      callback: interceptor
    }
  },
  []
);

图4-2-6-2 拦截器的申明入口

二、middleware

在项目初始化时使用CLI构建初始化前端工程,在src/middleware有拦截器的默认实现:

image.png

图4-2-6-3 在src/middleware有拦截器的默认实现

三、interceptor

interceptor在请求返回后触发,interceptor有两个回调函数,error和next

error参数

  • graphQLErrors 处理业务异常

  • networkError 处理网络异常

next

  • extensions 后端返回扩展参数
const interceptor: RequestHandler = (operation, forward) => {
  return forward(operation).subscribe({
    error: ({ graphQLErrors, networkError }) => {
            console.log(graphQLErrors, networkError);
      // 默认实现 => interceptor error 
    },
    next: ({ extensions }) => {
            console.log(extensions);
      // 默认实现 => interceptor next 
    },
  });
};

图4-2-6-4 后端返回扩展参数

四、interceptor error

// 定义错误提示等级
const DEFAULT_MESSAGE_LEVEL = ILevel.ERROR;
// 错误提示等级 对应提示的报错
const MESSAGE_LEVEL_MAP = {
  [ILevel.ERROR]: [ILevel.ERROR],
  [ILevel.WARN]: [ILevel.ERROR, ILevel.WARN],
  [ILevel.INFO]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO],
  [ILevel.SUCCESS]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS],
  [ILevel.DEBUG]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS, ILevel.DEBUG]
};
// 错误提示通用函数
const notificationMsg = (type: string = 'error', tip: string = '错误', desc: string = '') => {
  notification[type]({
    message: tip,
    description: desc
  });
};
// 根据错误等级 返回错误提示和类型
const getMsgInfoByLevel = (level: ILevel) => {
  let notificationType = 'info';
  let notificationText = translate('kunlun.common.info');
  switch (level) {
    case ILevel.DEBUG:
      notificationType = 'info';
      notificationText = translate('kunlun.common.debug');
      break;
    case ILevel.INFO:
      notificationType = 'info';
      notificationText = translate('kunlun.common.info');
      break;
    case ILevel.SUCCESS:
      notificationType = 'success';
      notificationText = translate('kunlun.common.success');
      break;
    case ILevel.WARN:
      notificationType = 'warning';
      notificationText = translate('kunlun.common.warning');
      break;
  }
  return {
    notificationType,
    notificationText
  };
};

error: ({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        graphQLErrors.forEach(async ({ message, locations, path, extensions }) => {
          let { errorCode, errorMessage, messages } = extensions || {};
          // FIXME: extensions.errorCode
          if (errorCode == null) {
            const codeArr = /code: (\d+),/.exec(message);
            if (codeArr) {
              errorCode = Number(codeArr[1]);
            }
          }
          if (errorMessage == null) {
            const messageArr = /msg: (.*),/.exec(message);
            if (messageArr) {
              errorMessage = messageArr[1];
            }
          }
          // 错误通用提示
          if (messages && messages.length) {
            messages.forEach((m) => {
              notificationMsg('error', translate('kunlun.common.error'), m.message || '');
            });
          } else {
            notificationMsg('error', translate('kunlun.common.error'), errorMessage || message);
          }
            // 提示扩展信息 根据错误等级来提示对应级别的报错
          const extMessage = getValue(response, 'extensions.messages');
          if (extMessage && extMessage.length) {
            const messageLevelArr = MESSAGE_LEVEL_MAP[DEFAULT_MESSAGE_LEVEL];
            extMessage.forEach((m) => {
              if (messageLevelArr.includes(m.level)) {
                const { notificationType, notificationText } = getMsgInfoByLevel(m.level);
                notificationMsg(notificationType, notificationText, m.message || '');
              }
            });
          }

          // 消息模块的用户未登录错误码
          const MAIL_USER_NOT_LOGIN = 20080002;
          // 基础模块的用户未登录错误码
          const BASE_USER_NOT_LOGIN_ERROR = 11500001;
          if (
            [MAIL_USER_NOT_LOGIN, BASE_USER_NOT_LOGIN_ERROR].includes(Number(errorCode)) &&
            location.pathname !== '/auth/login'
          ) {
            const redirect_url = location.pathname;
            location.href = `/login?redirect_url=${redirect_url}`;
          }
          /**
           * 应用配置异常跳转至通用的教程页面
           */
          // 模块参数配置未完成
          const BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR = 11500004;
          if ([BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR].includes(Number(errorCode))) {
            const action = getValue(response, 'extensions.extra.action');
            if (action) {
              Action.registerAction(action.model, action);
              const searchParams: string[] = [];
              searchParams.push(`module=${action.module}`);
              searchParams.push(`model=${action.model}`);
              searchParams.push(`viewType=${action.viewType}`);
              searchParams.push(`actionId=${action.id}`);
              const href = `${origin}/page;${searchParams.join(';')}`;
              location.href = href;
            }
          }
        });
      }
      if (networkError) {
        const { name, result } = networkError;
        const errMsg = (result && result.message) || `${networkError}`;
        if (name && result && result.message) {
          notification.error({
            message: translate('kunlun.common.error'),
            description: `[${name}]: ${errMsg}`,
          });
        }
      }
    }

图4-2-6-5 interceptor error

四、interceptor next

next: ({ extensions }) => {
  if (extensions) {
    const messages = extensions.messages as {
      level: 'SUCCESS';
      message: string;
    }[];
    if (messages)
      messages.forEach((msg) => {
        notification.success({
          message: '操作成功',
          description: msg.message,
        });
      });
  }
}

图4-2-6-6 interceptor next

六、完整代码

import { NextLink, Operation } from 'apollo-link';
import { notification } from 'ant-design-vue';
import getValue from 'lodash/get';
import { Action, ILevel, translate } from '@kunlun/dependencies';

interface RequestHandler {
  (operation: Operation, forward: NextLink): Promise<any> | any;
}

const DEFAULT_MESSAGE_LEVEL = ILevel.ERROR;
const MESSAGE_LEVEL_MAP = {
  [ILevel.ERROR]: [ILevel.ERROR],
  [ILevel.WARN]: [ILevel.ERROR, ILevel.WARN],
  [ILevel.INFO]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO],
  [ILevel.SUCCESS]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS],
  [ILevel.DEBUG]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS, ILevel.DEBUG]
};

const notificationMsg = (type: string = 'error', tip: string = '错误', desc: string = '') => {
  notification[type]({
    message: tip,
    description: desc
  });
};

const getMsgInfoByLevel = (level: ILevel) => {
  let notificationType = 'info';
  let notificationText = translate('kunlun.common.info');
  switch (level) {
    case ILevel.DEBUG:
      notificationType = 'info';
      notificationText = translate('kunlun.common.debug');
      break;
    case ILevel.INFO:
      notificationType = 'info';
      notificationText = translate('kunlun.common.info');
      break;
    case ILevel.SUCCESS:
      notificationType = 'success';
      notificationText = translate('kunlun.common.success');
      break;
    case ILevel.WARN:
      notificationType = 'warning';
      notificationText = translate('kunlun.common.warning');
      break;
  }
  return {
    notificationType,
    notificationText
  };
};

const interceptor: RequestHandler = (operation, forward) => {
  return forward(operation).subscribe({
    error: ({ graphQLErrors, networkError, response }) => {
      if (graphQLErrors) {
        graphQLErrors.forEach(async ({ message, locations, path, extensions }) => {
          let { errorCode, errorMessage, messages } = extensions || {};
          // FIXME: extensions.errorCode
          if (errorCode == null) {
            const codeArr = /code: (\d+),/.exec(message);
            if (codeArr) {
              errorCode = Number(codeArr[1]);
            }
          }
          if (errorMessage == null) {
            const messageArr = /msg: (.*),/.exec(message);
            if (messageArr) {
              errorMessage = messageArr[1];
            }
          }
          if (messages && messages.length) {
            messages.forEach((m) => {
              notificationMsg('error', translate('kunlun.common.error') || '', m.message || '');
            });
          } else {
            notificationMsg('error', translate('kunlun.common.error') || '', errorMessage || message);
          }

          const extMessage = getValue(response, 'extensions.messages');
          if (extMessage && extMessage.length) {
            const messageLevelArr = MESSAGE_LEVEL_MAP[DEFAULT_MESSAGE_LEVEL];
            extMessage.forEach((m) => {
              if (messageLevelArr.includes(m.level)) {
                const { notificationType, notificationText } = getMsgInfoByLevel(m.level);
                notificationMsg(notificationType, notificationText, m.message || '');
              }
            });
          }
          console.log(extMessage);

          // 消息模块的用户未登录错误码
          const MAIL_USER_NOT_LOGIN = 20080002;
          // 基础模块的用户未登录错误码
          const BASE_USER_NOT_LOGIN_ERROR = 11500001;
          if (
            [MAIL_USER_NOT_LOGIN, BASE_USER_NOT_LOGIN_ERROR].includes(Number(errorCode)) &&
            location.pathname !== '/auth/login'
          ) {
            const redirect_url = location.pathname;
            location.href = `/login?redirect_url=${redirect_url}`;
          }
          /**
           * 应用配置异常跳转至通用的教程页面
           */
          // 模块参数配置未完成
          const BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR = 11500004;
          if ([BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR].includes(Number(errorCode))) {
            const action = getValue(response, 'extensions.extra.action');
            if (action) {
              Action.registerAction(action.model, action);
              const searchParams: string[] = [];
              searchParams.push(`module=${action.module}`);
              searchParams.push(`model=${action.model}`);
              searchParams.push(`viewType=${action.viewType}`);
              searchParams.push(`actionId=${action.id}`);
              const href = `${origin}/page;${searchParams.join(';')}`;
              location.href = href;
            }
          }
        });
      }
      if (networkError) {
        const { name, result } = networkError;
        const errMsg = (result && result.message) || `${networkError}`;
        if (name && result && result.message) {
          notification.error({
            message: translate('kunlun.common.error') || '',
            description: `[${name}]: ${errMsg}`
          });
        }
      }
    }
  });
};

export default interceptor;

图4-2-6-7 完整代码

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9307.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

Like (0)
史, 昂's avatar史, 昂数式管理员
Previous 2024年5月23日 am8:31
Next 2024年5月23日 am8:33

相关推荐

  • 翻译

    翻译应用是管理翻译规则的应用,以模型为基础、维护字段的翻译值,支持导入、导出 1. 操作步骤 Step1:导出所有翻译项; Step2:线下翻译; Step3:导入翻译项; Step4:刷新远程资源; Step5:页面右上角可切换语言,查看翻译效果。 2. 新增翻译 翻译是具体到模型字段,其中需要区分出是否字典; 源语言、目标语言,是在资源中维护的语言,可在资源中维护需要翻译的语言; 翻译项则是模型字段,默认翻译项为激活状态,关闭后维护的翻译项无效。 3. 导出、导入 不勾选导出:导出所有需要翻译的翻译项,包括模块、字段,源术语、翻译值等,其中如果已经翻译过的内容,会体现在翻译值中; 勾选导出:导出勾选模型的翻译项。 导入:导入翻译项,平台会根据模型拆分为多条数据。 4. 刷新远程资源 导入翻译项后,点击“刷新远程资源”按钮。 5. 查看翻译内容 页面右上角切换语言,查看翻译效果。

    2024年6月20日
    1.3K00
  • 3.1.2 环境准备(windows版)

    一、后端基础环境准备 安装JDK1.8 ,高于1.8_221以上(下载地址见书籍【附件一】) 打开Windows环境变量配置页 此电脑 => 右键属性 => 系统高级设置 => 环境变量 配置环境变量 在用户环境变量中新建变量为JAVA_HOME的项,值为JDK安装之后的路径 图3-1-27 新建环境变量JAVA_HOM 编辑变量为Path的项添加一个值%JAVA_HOME%\bin 图3-1-28 添加一个环境变量值%JAVA_HOME%\\bin PowerShell或者CMD中验证,输出类似信息为安装配置成功 图3-1-29 验证JAVA是否安装成功 安装 Apache Maven 3.8+ (下载地址见书籍【附件一】) 删除Maven安装目录下的conf/settings.xml 配置mvn的settings,下载附件settings-open.xml,并重命名为settings.xml,建议直接放在【C:\Users\你的用户名.m2】下面。下载地址见oinone开源社区群公告,也可以联系oinone合作伙伴或服务人员 配置环境变量 在用户环境变量中新建变量为M2_HOME的项,值为Maven安装路径 图3-1-30 新建变量M2_HOME 编辑变量为Path的项添加一个值%M2_HOME%\bin 图3-1-31 添加一个值%M2_HOME%\\bin 验证 图3-1-32 验证Maven是否安装成功 安装 Jetbrains IDEA (下载地址见书籍【附件一】) 插件安装 下载地址 密码: mdji 如果IDEA安装了Lombok插件,请禁用Lombok插件 点击菜单项File => Settings => Plugins 图3-1-33 插件管理页面操作示意 下载插件包 (联系Oinone官方客服) 图3-1-35 操作指引 图3-1-36 操作指引 安装MySQL 8 (下载地址见书籍【附件一】) 解压下载的ZIP安装包, 复制到自定义安装目录 设置环境变量 MYSQL_BASE_DIR 提换成MySQL安装目录路径 把 %MYSQL_BASE_DIR%\bin 加入到系统环境变量中 在PowerShell中可以使用 Get-Command mysqld 命令验证环境变量是否配置成功,执行成功输出mysqld的所在路径 初始化 在命令行中执行 mysqld –initialize-insecure –user=mysql 安装 mysqld -install 启动MySQL服务 mysqld -install 设置root用户密码 alter user \’root\’@\’localhost\’ identified with mysql_native_password by \’oinone\’; flush privileges; 安装DB GUI工具 Datagrip、MySQLWorkbench、DBEaver 选其一 ### 安装Git (下载地址见书籍【附件一】) 安装GraphQL测试工具Insomnia(下载地址见书籍【附件一】) 安装RocketMQ(下载地址见书籍【附件一】) 修改安装目录下bin中对应文件的默认配置 a. runserver.cmd文件内容 -Xms2g -Xmx2g为 -Xms1g -Xmx1g b. runbroker.cmd文件内容 -Xms2g -Xmx2g为 -Xms1g -Xmx1g,以及-XX:G1HeapRegionSize=1m 启动RocketMQ NameServer命令 RocketMQ安装目录\bin\mqnamesrv.cmd start 启动RocketMQ Broker命令 RocketMQ安装目录\bin\mqbroker.cmd -n localhost:9876 停止 RocketMQ命令 mqshutdown.cmd broker mqshutdown.cmd namesrv 安装ElasticSearch 版本 8.4.1(下载地址见书籍【附件一】) (非必须) ES运行时需要JDK18及以上版本JDK运行环境, ES安装包中包含了一个JDK18版本 set JAVA_HOME=ES安装路径\jdk 启动 ES安装路径\bin\elasticsearch.bat 停止 ctrl+c 或者关闭cmd、PowerShell的窗口 安装Redis (下载地址见书籍【附件一】) 解压安装包到安装目录 在PowerShell进入到Redis安装目录 在PowerShell中执行.\redis-server.exe,输出图中类似信息(如下图3-35所示): 图3-1-37 验证redis是否安装成功 新开PowerShell窗口, 进入到Redis安装目录, 执行 .\redis-cli.exe回车,输入 ping 回车输出 PONG即表示Redis安装成功 图3-1-38 验证redis是否安装成功 Zookeeper安装(下载地址见书籍【附件一】) 解压安装, 在 PowerShell中执行 tar zxvf 安装包路径(tar.gz包) -C Zk安装目录 进入 Zk安装目录\conf\ 复制 zoo_sample.cfg文件为 zoo.cfg 修改zoo.cfg文件的内容 (其中dataDir需要自己设定) tickTime=2000…

    2024年5月23日
    3.3K00
  • 流程设计

    1.流程设计 进入流程设计页之后可以进行流程名称、流程说明的编辑,可以进行流程设计,流程参数配置,保存和发布。 1.1 流程配置 点击进入流程配置页面,若需要配置一些参数供流程使用,可在此添加和删除。删除流程参数时,若该参数已在流程中被使用则无法删除。参数支持文本、数值、日期、布尔四种类型。 1.2 保存 点击后流程设计进行存档,流程设计不完整也支持保存,下次进入流程设计回到保存的页面。 1.3 发布 第一次发布时右上角发布显示文字为发布流程,后续发布按钮显示文字为更新发布。发布后流程才会按照设计触发,首次发布和更新发布的逻辑一致,若流程中有未解决的错误则无法发布不成功,发布成功后页面跳转到显示全部流程的页面,流程状态为已启用、已更新。

    2024年6月20日
    1.5K00
  • 工作流

    1. 查看、处理流程 1.1 流程查看 流程管理页面共同点: 选项分类筛选 标签筛选 应用下拉选筛选 根据流程名称搜索 流程管理页面名词解释: 任务待办:当前登录用户未处理的流程节点 我发起的:当前登录用户人为触发的流程(模型触发) 抄送:抄送给当前登录用户的节点(审批/填写) 我已办结:由当前登录用户完成人工/自动同意、人工拒绝或人工填写的节点 无需办理:当前登录用户转交的任务/被退回、被撤销、被或签、被其他分支任务拒绝的还未办理的任务 1.2 流程处理 1.2.1 任务待办 任务待办中点击“审批/填写”会进入流程详情处理页面,主要展示 1. 操作区 2. 流程发起人及状态 3. 模型视图内容 4. 流程时间线及其他记录。 审批代办操作区可能包含“分享、同意、拒绝、退回、加签、转交、返回”,填写代办操作区可能包含“分享、转交、提交、暂存、返回”,审批/填写操作区包含哪些动作由流程设计决定。 1.2.2 我发起的 我发起的流程列表中主要分为进行中和已完成的流程。进行中的流程可以进行查看、催办、撤销的操作,已完成的流程可以进行查看操作。 查看我发起的流程,进入流程详情页面,也是根据流程状态展示对应操作功能,进行中的流程有分享、催办、撤销、返回按钮,已完成的流程有分享、返回按钮。 1.2.3 抄送 抄送列表中每条抄送只可以进行查看操作,查看进入流程的详情页面,有分享和返回的操作。 1.2.4 我已办结 我已办结列表中可以进行查看操作,查看进入代办的详情页面,可以进行分享和返回的操作。 1.2.5 无需办理 无需办理列表中可以进行查看操作,查看进入代办的详情页面,可以进行分享和返回的操作。 2. 流程运行记录查看 所有运行流程都会记录在流程运行记录中,可以根据流程的所属应用,流程名称,触发方式和状态进行搜索,流程运行记录详情中展示流程运行的具体节点,运行时间,当前运行节点,异常信息等。

    2024年6月20日
    2.2K00
  • 3.4 Oinone以函数为内在

    函数(Function):是oinone可管理的执行逻辑单元,跟模型绑定则对应模型的方法 描述满足数学领域函数定义,含有三个要素:定义域A、值域C{f(x),x属于A}和对应法则f。其中核心是对应法则f,它是函数关系的本质特征 满足面向对象原则,可设置不同开放级别,本地与远程智能切换。 本章会带大家更加详细地了解Function的方方面面,主要以几下几个维度 构建第一个Function 函数的开放级别与类型 函数的相关特性 函数元数据详解

    Oinone 7天入门到精通 2024年5月23日
    1.7K00

Leave a Reply

Please Login to Comment