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

相关推荐

  • 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
  • 开发者

    1.开发者 1.1 Webhook 通过webhook流程节点可以向第三方系统发送请求。 1.1.1 请求方式 支持GET、POST两种请求方式。 1.1.2 URL 在Webhook URL中填写发送请求的HTTP地址。 1.1.3 Headers&Body Headers的value支持通过表达式配置变量 Body的数据类型支持KEY_VALUE和APPLICATION_JSON两种。

    2024年6月20日
    1.1K00
  • 3.5.5 设计器的结合(改)

    在页面开发的时候,直接通过前端组件和视图xml进行开发虽然开放性是很大的、但我们经常会忘记视图的配置属性,同时用xml配置的页面因为缺少设计数据,导致无法直接在设计器中复制,自定义页面得从头设计。今天就带大家一起来学习如何结合无代码设计器来完成页面开发,并把设计后的页面元数据装载为标准产品的一部分。 1 安装Docker 如果没有Docker的话,请自行到官网下载:https://www.docker.com/get-started/ 2 下载Docker 镜像,并导入镜像 Step2.1 镜像下载 v.4.6.28.3-allinone-full 版本说明 前后端以及中间件一体 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-full 下载结构包 oinone-op-ds-all-full.zip(17 KB) v.4.6.28.3-allinone-mini 版本说明 前后端一体支持外部中间件 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-mini 下载结构包 oinone-op-ds-all-mini.zip(14 KB) v.4.7.9-allinone-full 版本说明 前后端以及中间件一体 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.7.9-allinone-full 下载结构包 oinone-op-ds-all-full.zip(17 KB) v.4.7.9-allinone-mini 版本说明 前后端一体支持外部中间件 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.7.9-allinone-mini 下载结构包 oinone-op-ds-all-mini.zip(14 KB) Step2.1.2 镜像下载用户与密码 需要商业版镜像需要加入Oinone商业版本伙伴专属群,向Oinone技术支持获取用户名与密码,镜像会定时更新并通知大家。 #注意:docker镜像拉取的账号密码请联系数式技术 docker login –username=用户名 harbor.oinone.top docker pull docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-full Step2.1.3 镜像和版本选择 目前有2个版本可供选择,包含中间件以及不包含中间件2个版本,下载结构包以后注意修改startup.sh和startup.cmd中对应镜像地址的版本号。 Step2.1.4 本地结构说明 下载结构包并解压 config是放application.yml的目录,可以在application.yml配置需要启动的自有模块同时修改对应其他中间件配置项 lib是放自有模块的jar包以及其对应的依赖包比如:pamirs-demo-api-1.0.0-SNAPSHOT.jar和pamirs-demo-core-1.0.0-SNAPSHOT.jar nginx:前端运行的nginx站点配置文件 mq:消息配置,再使用低无一体时需要指定mq的broker的IP run:容器运行中间件的脚本,可以对个别中间件是否启动进行设置,(注释掉运行脚本,容器启动时就不会启动该中间件) logs是运行时系统日志目录 Step2.2 修改startup.sh中的路径 Step2.2.1 linux环境修改参数 在文件中找到如下 configDir=/opt/docker/oinone-op-ds-all-full version=4.6.28.3 IP=192.168.0.121 修改configDir的路径(下载oinone-op-ds-xx.zip解压后的路径) 修改对应的镜像版本号 修改对应的IP为docker宿主机IP #!/bin/bash configDir=/opt/docker/oinone-op-ds-all-full version=4.6.28.3 IP=192.168.0.121 docker run -d –name designer-allinone \ -e DUBBO_IP_TO_REGISTRY=$IP \ -e DUBBO_PORT_TO_REGISTRY=20880 \ -p 8099:8091 \ -p 3307:3306 \ -p 2182:2181 \ -p 6378:6379 \ -p 19876:9876 \ -p 10991:10991 \ -p 15555:15555 \ -p 20880:20880 \ -p 88:80 \ -v $configDir/config/:/opt/pamirs/ext \ -v $configDir/nginx:/opt/pamirs/nginx/vhost \ -v $configDir/logs:/opt/pamirs/logs \ -v $configDir/mq/broker.conf:/opt/mq/conf/broker.conf \ -v $configDir/run/run.sh:/opt/pamirs/run/run.sh \ -v $configDir/lib:/opt/pamirs/outlib harbor.oinone.top/oinone/designer:$version-allinone-full Step2.2.3 window环境修改参数 在文件中找到如下 set configDir=/d/shushi/docker/oinone-op-ds-all-full set version=4.6.28.3 set IP=192.168.0.121 修改configDir的路径((下载oinone-op-ds-xx.zip解压后的路径) 修改对应的镜像版本号 修改对应的IP为docker宿主机IP @echo off set configDir=/d/shushi/docker/oinone-op-ds-all-full set version=4.6.28.3 set IP=192.168.0.121 docker run -d –name designer-allinone ^ -e DUBBO_IP_TO_REGISTRY=%IP% ^ -e DUBBO_PORT_TO_REGISTRY=20880 ^ -p 8099:8091…

    2024年5月23日
    1.0K00
  • 3.2.3 应用中心

    在App Finder 中点击应用中心可以进入oinone的应用中心,可以看到oinone平台所有应用列表、应用大屏、以及技术可视化。 一、应用列表 标准版本不支持在线安装,只能通过boot工程的yml文件来配置安装模块。在 www.oinone.top 官方SaaS平台客户可以在线管理应用生命周期如:安装、升级、卸载。同时针对已安装应用可以进行无代码设计(前提安装了设计器),针对应用类的模块则可进行收藏,收藏后会在App Finder中的我收藏的应用中出现。在应用列表中可以看到我们已经安装的应用以及模块,我们oinoneDemo工程也在其中。 图3-2-35 Oinone的应用列表 图3-2-36 应用收藏后会在App Finder的【我收藏的应用】中出现 二、应用大屏 但我们的测试应用没有设置应用类目,则无法在应用大屏中呈现。 图3-2-37 未设置应用类目则无法在应用大屏中呈现 三、技术可视化 在技术可视化页面,出展示已经安装模块的元数据,并进行分类呈现 图3-2-38 云数据分类呈现

    2024年5月23日
    1.5K00
  • 5.8 商业支撑之执行域

    一、基础介绍 执行域包括两个核心一是订单的产生,二是订单的履约。往往品牌商既有自营渠道(包括2c、2b)、又有第三方渠道。那么有两种设计思路: 把第三方渠道的订单当作自有渠道的订单产生一种特殊方式,开放订单创建接口,并统一履约。 好处:简单,在3方渠道不多、且自有渠道单一,并且逻辑相识时系统结构会简单 坏处: 当3方渠道的履约方式、库存分配方式、逆向逻辑等有差异时,会让自有渠道参杂很多不相干的逻辑引入不必要的复杂度 自有渠道不够独立和纯粹,自有渠道多样化时难以支撑 把商家自营渠道假设为特殊的第三方渠道,再建立统一的订单管理系统来对接渠道订单,并完成履约 好处:交易与履约逻辑分离,对未来发展有扩展性 坏处:引入一定复杂度 我们采用的是第二套方案,整体结构简易图如下 图5-8-1 方案整体结构简易图 二、模型介绍 图5-8-2 模型介绍 核心设计逻辑 首先我们看到上图交易域和履约域有很多相同父模型的子模型,交易域和履约域的父模型在CDM的在himalaya-trade里。履约域看oms(libra)对himalaya-trade扩展,交易域看b2c(leo)和b2b(aries)对对himalaya-trade扩展。libra、leo、aries是我们对上层业务产品的命名,取自黄道十二星座 交易域是多商家平台视角设计,有自身渠道必要的履约相关信息,完成自闭环。 履约域是从单一商家对接多渠道视角设计,有渠道交易订单同步后完成履约发货相关设计,完成自闭环。 履约域的合单拆单发货设计,渠道订单只能合单为履约单不可拆,履约单可以拆单发货不可合。用m2o和o2m的组合设计来降低难度,而非采用两个m2m的设计。

    2024年5月23日
    95500

Leave a Reply

登录后才能评论