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低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:31
下一篇 2024年5月23日 am8:33

相关推荐

  • 书籍封面

    2024年5月23日
    3.2K00
  • 3.5.6.2 视图的配置

    ,视图的大致配置在3.5.2.2【构建View的Template】一文中已经介绍过,这里主要介绍视图层的基本属性配置,这些配置会透传给视图内的组件Widget,组件会根据配置内容做出不同的呈现样式 视图的配置 Table的配置 配置项 可选值 默认值 作用 activeCount number 5 表格上方动作区默认展示操作的数量,超过个数的操作将被折叠收起 inlineActiveCount number 3 表格最右侧操作列默认展示操作的数量,超过个数的操作将被折叠收起 defaultPageSize number 30 表格默认分页条数 表3-5-6-9 Table的配置 Form/Detail的配置 配置项 可选值 默认值 作用 direction horizontal/vertical(大小写不明感) vertical 表单标题排列方式 表3-5-6-10 Form/Detail的配置 Table的配置项举例 Step1 修改宠物达人的表格视图 我们在宠物达人的自定义表格视图的Template文件中增加三个属性配置activeCount="1" 、inlineActiveCount="1"、 defaultPageSize="1" <view name=tableView model=demo.PetTalent cols=1 activeCount=1 inlineActiveCount=1 defaultPageSize=1 type=TABLE enableSequence=true > </view> 图3-5-6-15 在宠物达人的自定义表格视图的Template文件中增加三个属性配置 Step2 重启看效果 图3-5-6-16 示例效果 Form的配置举例 Step1 修改宠物达人的表单视图 我们在宠物达人的自定义表格视图的Template文件中增加一个属性配置direction = horizontal 。 另:宠物达人在之前的教程中增加了一些字段,大家利用默认视图把新增字段也展示出来。还是通过数据库查看默认页面定义,找到base_view表,过滤条件设置为model =\’demo.PetTalent\’ and name =\’formView\’,查看template字段,把里面涉及新增字段复制到pet_talent_form.xml文件中。 <view name=formView1 model=demo.PetTalent cols=2 type=FORM priority=1 direction = horizontal> </view> 图3-5-6-17 增加一个属性配置direction = "horizontal" Step2 重启看效果 图3-5-6-18 示例效果

    2024年5月23日
    1.1K00
  • 3.2 Oinone以模块为组织

    模块(module):是按业务领域划分和管理的最小单元,是一组功能、界面的集合。 带大家快速认识下如何构建一个oinone的模块并启动它。我会从以下几个维度去介绍模块的构建与启动方式、模块详解。让大家直观且全方位地了解oinone的模块所包含的内容 构建第一个Module 启动前端工程 应用中心

    Oinone 7天入门到精通 2024年5月23日
    1.7K00
  • 3.1.1 环境准备(Mac版)

    工欲善其事,必先利其器。 在进行学习前,大家务必先检查环境。为了降低大家环境准备难度,基础环境全程用安装包无脑模式进行环境配置,安装请从附件下载(提供mac版本安装包,其他操作系统请自行网上下载与安装)。 后端相关 基础环境准备 安装 jdk 1.8 (下载地址见书籍【附件一】) 安装 mysql 8.0.26 (下载地址见书籍【附件一】) 安装mysql,并配置环境变量详见本文中的【环境变量设置】部分 如果mysql启动失败则,在命令行加执行以下命令 Shell mysqld –initalize-insecure sudo chmod -R a+rwx /usr/local/mysql/data/ 图3-1-1 mysql启动失败需执行的命令 安装 idea社区版 (官方下载链接见书籍【附件一】) 根据不同版本下载不同的idea插件 (联系Oinone官方客服) b. 点击Preferences菜单(快捷键 comand+,) c. 选择Plugins,进入插件管理页面,接下来按图操作就可以了 d. 图3-1-3 插件管理页面操作示意 e. 选择.zip文件,不需要解压 如果安装了Lombok,请禁用 idea的Java Complier,不然java反射获取方法入参名会变成arg*,导致元数据默认取值出错。或者pom中加入Complier插件,此方法为正解,不然上线也会有问题,我们学习的工程都会选用mvn插件方式 图3-1-4 界面操作示意图 图3-1-5 界面操作示意图 图3-1-6 界面操作示意图 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerArgument>-parameters</compilerArgument> <source>${maven.compiler.source}</source> <target>${maven.compiler.source}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> 图3-1-7 pom文件代码 安装 dataGrip 最新版本的 过期就去删“ ~/Library/Application\ Support/JetBrains/DataGrip202xxxx”相关的目录,无限期试用,或者安装其他mysql GUI 工具 安装 git 2.2.0(下载地址见书籍【附件一】) 安装 GraphQL的客户端工具 Insomnia 第一次使用可以参考3.2.1【构建第一个Module】一文中在模块启动后如何用该工具验证后端启动成功,更多使用技巧自行百度,Insomnia.Core-2022.4.2.dmg.txt(186.9 MB)(下载地址见书籍【附件一】),下载文件后修改文件名去除.txt后缀 安装 maven ,并配置环境变量(下载地址见书籍【附件一】) 配置mvn的settings,下载附件settings-open.xml,并重命名为settings.xml,建议直接放在~/.m2/下面。下载地址见oinone开源社区群公告,也可以联系oinone合作伙伴或服务人员 把settings.xml拷贝一份到maven安装目录conf目录下 环境变量设置 vi ~/.bash_profile ,并执行 source ~/.bash_profile ##按实际情况设置 export PATH=$PATH:/usr/local/mysql/bin export PATH=$PATH:/usr/local/mysql/support-files export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_0221.jdk/Contents/Home ##替换掉${mavenHome},为你的实际maven的安装路径 export M2_HOME=${mavenHome} export PATH=$PATH:$M2_HOME/bin 图3-1-8 环境变量设置 查看主机名 #查看主机名 echo $HOSTNAME 图3-1-9 查看主机名 根据主机名,配置/etc/hosts文件。此步如果没有配置,可能导致mac机器在启动模块时出现dubbo超时,从而导致系统启动巨慢,记得把oinonedeMacBook-Pro.local换成自己的主机名 #oinonedeMacBook-Pro.local 需要换成自己对应的主机名,自己的主机名用 echo $HOSMNAME 127.0.0.1 oinonedeMacBook-Pro.local ::1 oinonedeMacBook-Pro.local 图3-1-10 配置/etc/hosts文件 必备中间件安装脚本(rocketmq、zk、redis) zk 下载并解压(下载地址见书籍【附件一】) vi ~/.bash_profile ,追加以下两行,并执行 source ~/.bash_profile #### 替换掉${basePath},为你的实际安装路径 export ZOOKEEPER_HOME=${basePath}/apache-zookeeper-3.5.8-bin export PATH=$PATH:$ZOOKEEPER_HOME/bin 图3-1-11 配置zk环境变量 启动zk ##启动 zkServer.sh start ##停止 zkServer.sh stop 图3-1-12 启停zk rocketmq (下载地址见书籍【附件一】) vi ~/.bash_profile ,追加以下两行,并执行 source ~/.bash_profile #### 替换掉${basePath},为你的实际安装路径 export ROECET_MQ_HOME=${basePath}/rocketmq-all-4.7.1-bin-release export PATH=$PATH:$ROECET_MQ_HOME:$ROECET_MQ_HOME/bin 图3-1-13 配置rocketmq环境变量 到bin目录下修改配置文件 runserver.sh 和 runbroker.sh ##注释掉下面一行 ##choose_gc_log_directory ##修改java启动所需内存,按自己实际情况改,1g或者512m JAVA_OPT = "${JAVA_OPT} -server -Xms1g -Xmx1g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m" 图3-1-14 bin目录下修改配置文件 启停rocketmq ##启动 nameserver nohup…

    2024年5月23日
    1.8K00
  • 3.5.5.1 设计器数据导出

    简介 通过调用导出接口,将设计器的设计数据与运动数据打包导出到文件中。 提供了download/export两类接口。 export 导出到OSS。导出的文件会上传到文件服务,通过返回的url下载导出文件。 请求示例: mutation { uiDesignerExportReqMutation { export( data: { module: "gemini_core", fileName: "meta", moduleBasics: true } ) { jsonUrl } } } 响应示例: { "data": { "uiDesignerExportReqMutation": { "export": { "jsonUrl": "https://xxx/meta.json" } } }, "errors": [], "extensions": {} } download 直接返回导出数据。适用于通过浏览器直接下载文件。 请求示例: mutation { uiDesignerExportReqMutation { download( data: { module: "gemini_core", fileName: "meta", moduleBasics: true } ) { jsonUrl } } } 如何构造url protocol :// hostname[:port] / path ? query=URLEncode(GraphQL) 例: http://127.0.0.1:8080/pamirs/base?query=mutation%20%7B%0A%09uiDesignerExportReqMutation%20%7B%0A%09%09download(%0A%09%09%09data%3A%20%7B%20module%3A%20%22gemini_core%22%2C%20fileName%3A%20%22meta%22%2C%20moduleBasics%3A%20true%20%7D%0A%09%09)%20%7B%0A%09%09%09jsonUrl%0A%09%09%7D%0A%09%7D%0A%7D 在浏览器中访问构造后的url,可直接下载文件 接口列表 模型设计器 指定模块导出 query { modelMetaDataExporterQuery { export/download(query: { module: "模块编码" }) { module url } } } module参数:指定导出的模块编码 url返回结果:export方式导出的文件url 页面设计器 导出页面 指定模块导出 mmutation { uiDesignerExportReqMutation { download/export( data: { module: "gemini_core", fileName: "meta", moduleBasics: false } ) { jsonUrl } } } module参数:模块编码 fileName参数:指定生成的json文件名称 moduleBasics参数:指定是否只导出模块基础数据,如果为true,只导出内置布局、模块菜单、菜单关联的动作。 如果为false,还会导出模块内的所有页面,以及页面关联的动作元数据、页面设计数据 等等。 默认值为false。 指定菜单导出 mutation { uiDesignerExportReqMutation { download/export( data: { menu: { name: "uiMenu0000000000048001" } fileName: "meta" relationViews: true } ) { jsonUrl } } } menu参数:菜单对象,指定菜单的name。只会导出该菜单及其绑定页面,不会递归查询子菜单 fileName参数:指定生成的json文件名称 relationViews参数:指定是否导出关联页面,默认为false,只导出菜单关联的页面。如果为true,还会导出该页面通过跳转动作关联的自定义页面。 指定页面导出 mutation { uiDesignerExportReqMutation { download/export( data: { view: { name: "xx_TABLE_0000000000119001" model: "ui.designer.TestUiDesigner" } fileName: "meta" relationViews: true } ) { jsonUrl } } }…

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

Leave a Reply

登录后才能评论