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

相关推荐

  • 业务审计

    整体介绍 业务审计是指通过跟踪用户在平台业务应用中的各类行为操作以及关联的数据变化,支撑企业业务审计所需。平台提供可视化审计规则配置,根据审计规则记录行为日志,其中日志包括登录日志、应用日志; 登录日志:记录平台用户登录行为。 应用日志:针对已订阅的审计规则记录用户操作信息,是用户在各应用中操作行为留痕记录。 审计规则:业务审计中,数据变化订阅记录的规则,是记录应用日志的规则。 操作入口:应用中心——业务审计应用。

    Oinone 7天入门到精通 2024年6月20日
    1.1K00
  • 应用审计

    1. 整体介绍 应用审计是基于模型字段记录用户操作留痕记录,通过定义审计规则,平台基于审计规则订阅的字段记录形成日志。平台名词概念: 应用日志:针对已订阅的审计规则记录用户操作信息,是用户在各应用中操作行为留痕记录。 审计规则:业务审计中,数据变化订阅记录的规则。 操作入口:应用中心——业务审计应用。 2. 审计规则 审计规则是指定义审计过程订阅数据变化的信息,根据模型、订阅到具体字段内容变化形成应用日志。如订阅销售订单的备注,销售订单S20231001888,订单备注【尽快发货】,备注修改为【需易碎品包装】,审计规则为:销售订单模型,订阅【备注】。 操作包括:新增、编辑、删除。 2.1. 新增 新增时,定义审计规则名称,选择需要审计的模型,指定需要订阅的字段信息,同时可以指定关联关系的字段。 需要注意:每个模型仅限定义单条审计规则。 2.2. 编辑 编辑同新增操作,不做赘述。 2.3. 删除 删除规则后,平台将不再监听对应数据的变更日志,请慎重删除。 3. 应用日志 应用日志是针对已订阅的审计规则记录用户操作信息。记录操作用户、IP、登录设备、位置、订阅的字段变化内容。 应用日志详情 4. 业务表达 4.1. 展示效果 表格-行操作—日志记录 详情—日志记录 4.2. 操作步骤 Step1:在应用中心,需要维护业务应用依赖业务审计应用; 操作入口:应用中心,找到业务应用——编辑,依赖模块选择业务审计。 Step2:配置审计规则; 操作入口:业务审计应用——审计规则——新增规则。 Step2:界面设计器配置日志记录; 操作入口:界面设计器,找到需要配置的页面——模型组件,将动作区的日志记录拖动到页面中。

    2024年1月20日
    1.0K00
  • 高级组件

    本篇主要结合业务场景介绍高级组件的使用方法。 级联选择/树选择 级联选择与树选择是同一类业务场景、不同的交互体验,在这里我们一起说明。 业务场景 行业分类、产品类目/分类等自关联场景,案例以行业分类说明。 操作步骤 Step1:搭建模型 搭建行业模型,在行业模型中创建多对一字段“上级行业”,指多个子行业对应一个上级行业。如下图: Step2:界面设计 创建行业的表格视图,绑定菜单,并且在此视图中增加“跳转动作 – 新增行业”; 创建新增行业表单,将“上级行业”拖进画布中,组件切换为“级联选择”,属性面板配置“选项字段、搜索字段、透出字段”,平台低代码为每个模型自动生成了名称、编码字段,如果不使用平台提供的名称、自建名称时,需要配置这三个字段; 为“上级行业”设置联动关系,自关联默认选择行业、标题定义为行业名称、自关联的字段为上级行业。 配置后发布表格、表单视图,即可获得级联选择效果。 表单视图中将“上级行业”切换为“树选择”组件,在发布后,即可获得树选择效果。 Step3:效果展示 级联选择 树选择

    2024年6月20日
    1.1K00
  • 4.1.4 模块之元数据详解

    介绍Module相关元数据,以及对应代码注解方式。大家还是可以通读下,以备不时之需 如您还不了解Module的定义,可以先看下2.3【oinone独特之源,元数据与设计原则】一文对Module的描述,本节主要带大家了解Module元数据构成,能让小伙伴非常清楚oinone从哪些维度来描述Module, 一、元数据说明 ModuleDefinition 元素数据构成 含义 对应注解 备注 displayName 显示名称 @Module( displayName=””, name=””, version=””, category=””, summary=””, dependencies={“”,””}, exclusions={“”,””}, priority=1L ) name 技术名称 latestVersion 安装版本 category 分类编码 summary 描述摘要 moduleDependencies 依赖模块编码列表 moduleExclusions 互斥模块编码列表 priority 排序 module 模块编码 @Module.module(“”) dsKey 逻辑数据源名 @Module.Ds(“”) excludeHooks 排除拦截器列表 @Module.Hook(excludes={“”,””}) website 站点 @Module.Advanced( website=”http://www.oinone.top”, author=”oinone”, description=”oinone”, application=false, demo=false, web=false, toBuy=false, selfBuilt=true, license=SoftwareLicenseEnum.PEEL1, maintainer=”oinone”, contributors=”oinone”, url=”http://git.com” ) author module的作者 description 描述 application 是否应用 demo 是否演示应用 web 是否web应用 toBuy 是否需要跳转到website去购买 selfBuilt 自建应用 license 许可证 默认PEEL1 可选范围: GPL2 GPL2ORLATER GPL3 GPL3ORLATER AGPL3 LGPL3 ORTHEROSI PEEL1 PPL1 ORTHERPROPRIETARY maintainer 维护者 contributors 贡献者列表 url 代码库的地址 boot 是否自动安装的引导启动项 @Boot 加上该注解代表: 启动时会自动安装,不管yml文件的modules是否配置 moduleClazz 模块定义所在类 只有用代码编写的模块才有 packagePrefix 包路径,用于扫描该模块下的其他元数据 dependentPackagePrefix 依赖模块列对应的扫描路径 state 状态 系统自动计算,无需配置 metaSource 元数据来源 publishCount 发布总次数 platformVersion 最新平台版本 本地与中心平台的版本对应。做远程更新时会用到 publishedVersion 最新发布版本 表4-1-4-1 ModuleDefinition UeModule 是对ModuleDefinition的继承,并扩展了跟前端交互相关的元数据 元素数据构成 含义 对应注解 备注 homePage Model 跳转模型编码 @UxHomepage(@UxRoute() 对应一个ViewAction,如果UxRoute只配置了模型,则默认到该模型的列表页 homePage Name 视图动作或者链接动作名称 logo 图标 @UxAppLogo(logo=””) 表4-1-4-2 UeModule 二、元数据,代码注解方式 Module Module ├── displayName 显示名称 ├── name 技术名称 ├── version 安装版本 ├── category 分类编码 ├── summary 描述摘要 ├── dependencies 依赖模块编码列表 ├── exclusions 互斥模块编码列表 ├── priority 排序 ├── module 模块编码 │ └── value ├── Ds 逻辑数据源名 │ └── value ├── Hook 排除拦截器列表…

    Oinone 7天入门到精通 2024年5月23日
    1.1K00
  • 4.1.1 模块之yml文件结构详解

    本节是对demo的boot工程的application-*.yml文件关于oinone相关配置的扩充讲解,大家可以先通读留个影响,以备不时之需 在基础入门的模块一章中大家构建,并通过启动前后应用,直观地感受到我们自己建的demo模块。在上述过程中想必大家都了解到我们oinone的boot工程是专门用来做应用启动管理,它完全没有任何业务逻辑,它只决定启动哪些模块、启动方式、以及相关配置。它跟Spring Boot的一个普通工程没有什么差异。所有我们只要看application-*.yml文件,oinone提供了哪些特殊配置就能窥探一二。 这里主要介绍pamirs路径下的核心以及常用的配置项 一、pamirs.boot pamirs.boot.init 描述:启动加载程序,是否启动元数据、业务数据和基础设施的加载与更新程序,在应用启动时同时对模块进行生命周期管理 true ##标准版,只支持true pamirs.boot.sync 描述:同步执行加载程序,启动时对模块进行生命周期管理采用同步方式 true ##标准版,只支持true pamirs.boot.modules a. 描述:启动模块列表。这里只有base模块是必须的。为了匹配我们的前端模版,在demo的例子中加入了其他几个通用业务模块。当然这些通用业务模块也是可以大大降低大家的开发难度以及提升业务系统的设计质量 b. – base #oinone的基础模块 c. – common #oinone的一些基础辅助功能 d. – sequence #序列的能力 e. – resource #基础资源如 f. – user #基础用户 g. – auth #权限 h. – message #消息 i. – international #国际化 j. – business #商业关系 k. – file #文件,demo里没有默认加入,如果要开发导入导出相关功能,可以对应引入改模块 l. – …… 还有很多通用业务模块以及这些模块的详细介绍,我们在介绍第六章【oinone的通用能力】的章节去展开 pamirs.boot.mode ⅰ. dev:不走缓存,可以直接修改元数据。特别是我们在说页面设计的时候,可以修改base_view表直接生效不需要重启系统 配置举例 pamirs: boot: init: true sync: true modules: – base – common – sequence – resource – user – auth – message – international – business – demo_core 图4-1-1-1 pamirs.boot.mode配置举例 二、pamirs.boot.profile与pamirs.boot.options pamirs.boot.option, 在pamirs.boot.options中可以自定义可选项,也可以根据pamirs.boot.profile属性来指定这些可选项,pamirs.boot.profile属性的默认值为CUSTOMIZE。只有pamirs.boot.profile=CUSTOMIZE时,才能在pamirs.boot.options中自定义可选项。 可选项 说明 默认值 AUTO READONLY PACKAGE DDL reloadModule 是否加载存储在数据库中的模块信息 false true true true true checkModule 校验依赖模块是否安装 false true true true true loadMeta 是否扫描包读取模块元数据 true true false true true reloadMeta 是否加载存储在数据库中元数据 false true true true true computeMeta 是否重算元数据 true true false true true editMeta 编辑元数据,是否支持编程式编辑元数据 true true false true true diffMeta 差量减计算元数据 false true false true false refreshSessionMeta 刷新元数据缓存 true true true true true rebuildHttpApi 刷新重建前后端协议 true true true false false diffTable 差量追踪表结构变更 false true false true false rebuildTable 更新重建表结构 true true false true false…

    2024年5月23日
    1.2K00

Leave a Reply

登录后才能评论