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

相关推荐

  • 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.6K00
  • 第3章 Oinone的基础入门

    本章主要介绍如何快速入门,了解如何在Oinone上进行开发。我们将通过准备环境、构建自己的第一个Oinone模块、完成一些小功能等方式来全面了解Oinone,这将是一个很好的开始。 具体来说,本章包括以下几个方面: 环境搭建:准备Windows或Mac版环境。 Oinone以模块为组织:了解Oinone模块的概念和如何创建和使用模块。 Oinone以模型为驱动:了解Oinone模型的概念和如何使用模型来构建应用。 Oinone以函数为内在:了解Oinone函数的概念和如何使用函数来实现应用逻辑。 Oinone以交互为外在:了解Oinone交互的概念和如何使用交互来设计和实现应用界面。

    Oinone 7天入门到精通 2024年5月23日
    1.6K00
  • 3.4.3 函数的相关特性

    本小章会从oinone的函数拥有三方面特性,展开介绍 面向对象,继承与多态 面向切面编程,拦截器 SPI机制,扩展点

  • 庄卓然

    从2009年加入阿里至今,经历了“三淘”时期、天猫时期、双十一,到最后的all in无线手淘时期,几乎是赶上了淘系发展的所有历史性事件。在这个过程中,每一次业务的变革都催生着技术的变迁,倒逼着我们用技术的方式去解决业务问题:在存储、IO、网络等环节满足不了淘系的业务规模时,开始去IOE,最后演化成了阿里云;当业务的规模大到不能通过简单加机器的方式去做调整、当开发的规模大到所有人在一起开发会互相影响的的时候,我们开始做SOA改造,最后演化成了业务中台;在经历了几届双十一后的巨大挑战后,我们开创了里程碑式的全链路压测;在手淘时代,为了解决动态发版问题,我们植入容器概念,搭建了可动态插拔的三层架构,一年实现了500多次的发版;为了同时满足写一套代码就解决多端开发和高并发的性能问题,我们做了weex,最后还捐给了开源社区…… 每一次的业务需求推动技术进步,而技术的进步永远会超出我们的想象! 同为技术宅,我在Oinone身上能清晰地感受到技术演进的脉络,企业在数字化时代,需要一个能快速上手、全面设计、灵活适应且低成本的技术工具,时代的变迁推动了Oinone的诞生。Oinone是一种全新的开发方式,在数字化时代,Oinone在提升研发效率上做出的创新性“低无一体”的设计对传统软件代码开发或者无代码开发一定会有巨大冲击,这种冲击会对软件市场格局造成什么样的变化,我拭目以待。 最后,愿我们这些追光人,在时代的洪流中,都能留下一抹印迹,不辜负时代,不辜负自己。 现任阿里巴巴副总裁,飞猪总裁,曾任阿里大文娱CTO兼优酷COO、淘宝CTO 庄卓然(南天)

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

Leave a Reply

登录后才能评论