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

相关推荐

  • 高级组件

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

    2024年6月20日
    1.1K00
  • 构件类

    1.构件类 1.1 延时 当下一个节点动作需要一段时间之后再发生时,可以使用延时节点。延时节点包含两种延时方式:1、延至指定日期,2、延时一段时间。 选择延至指定日期时,可以选择延至模型字段的时间或自定义时间,如果模型字段只包含日期则必填指定时辰。如果选择自定义则需要分别指定日期和时辰。 选择延时一段时间时,至少需要填“天、小时、分钟”中的一项。 1.2 条件分支 使不同条件的数据执行不同的分支流程。需要设置分支条件、添加满足条件的动作、也可以增删条件分支。 必须将分支条件填写完整流程才能正常进行。当只有两个分支时点击删除任一分支会删除整个条件分支。 1.3 审批分支 审批分支是一种特殊的条件分支。审批分支只能添加在审批节点下方。因为审批只存在通过和拒绝两种条件,所以无法添加其他条件,并且点击任意条件的叉都会删除整个条件分支。同时若审批节点被删除,审批分支也会同时删除。 1.4 子流程 一些高度重复的流程节点可以创建成子流程,在主流程中引用子流程,减少流程的重复配置。选择子流程时只能选择当前流程中有用到的模型下并且在启用状态的子流程,也可以在创建子流程节点处设置新增子流程。子流程的执行方式有两种:子流程可以和后续节点同时执行,也可以设置子流程执行完后再执行后续节点。 子流程与普通正常流程不同,不包含触发方式,普通流程流转到子流程节点即为子流程的触发条件,添加完节点动作之后发布即可。在不新增数据的情况下,子流程中只能使用该子流程对应模型的字段数据。

    2024年5月23日
    1.0K00
  • 5.7 商业支撑之库存域

    库存的差异会反馈到企业的整个价值链上,所以对库存的设计是至关重要的 一、基础介绍 我们先抛开仓库中对库存的实操管理和整个流通领域的库存,只围绕企业自身一级的采销链路上我们可以从管理和销售两个角度去看。 从管理角度上我们会关心:实物库存、在途库存、在产库存、库存批次等等,也就是企业有多少库存分布在哪里在什么环节。 从销售角度上我们会关心:可售库存、安全库存等等,也就是企业在特定渠道销售中库存分配规则。 在商业场景中库存管理一头对接仓库、生成、采购,另一头对接多个销售渠道。它的挑战在于不同行业不同特征商品都有比较大的差异。比如家具行业卖的是生产能力,家电区域化销售,生鲜拼车销售,服饰一仓销全国。热销的要分配提升体验防止超卖,滞销的要活动拉流量,普通的要渠道共享最大化可售。库存管理的差异会反馈到企业的整个价值链上,所以对库存的设计是至关重要的。 库存设计挑战在于: 技术上:库存类似账户账本的设计,需要能追溯库存变化的过程,且库存操作都能可追溯业务单据。热点数据的并发控制 业务上:在管理角度上游能跟仓库、采购、生产等进行对接、对账、并为其设置可售规则,下游能为各个销售渠道设置库存分配与同步规则 二、模型介绍 图5-7-1 模型介绍 核心设计逻辑: 单据链路:业务单据(外部业务单据+库存业务单据)产生库存指令(库存调整入\出库单),再由库存指令操作库存并记录库存流水。 管理链路:基础数据维护仓库、供应商、服务范围与费用。这些数据是订单履约路由和可售库存同步的基础 库存数据:对外跟商品域,通过库存指令进行操作。不同库存各自维护自身库存与流水记录,确保可追溯。 如果跟销售渠道对接,还需要扩展可售库存逻辑规则以及同步规则。比如oms类似的应用

    2024年5月23日
    93100
  • 特别说明

    教材进度 目前还在编写整改中,特别是目录上带(改)字样的 本版本教材针对4.0,相对3.0增加的特性有: 通用能力部分:比如权限、审计、国际化、系统配置、集成可视化等 新版权限:交互优化,同时支持子管理员 新版审计,支持在线配置审计规则 系统配置,提供多种风格,让伙伴基础风格不在需要自定义主题和组件 新增集成设计器,通过连接器让应用api和数据库集成资产化管理,通过数据流进行接口逻辑编排,并提供统一的开放平台 设计器部分: 加强界面设计器部分对移动端、主题、自定义组件等支持,同时完善对数据管理操作、增加各类常用业务组件,加强对树形与及联的支持,表格视图搜索优化 流程设计器增加:审批员选择自定义逻辑、转交人选择自定义逻辑,支持手工触发、支持数据事务、支持调用模型函数 可视化设计器:增加自定义图表功能、增强下钻能力 模块管理:增加新增、多端配置等支持 内核机制: 性能优化:通过gql层面解决业务研发过程中1+N性能问题,权限性能优化,分布式缓存性能优化,整体性能提升2倍以上 针对多租户应用无状态的支持,低无一体支持本地调试 5.0的核心新特性预告,特性会在开发过程中陆续推出供大家体验,但完整体验时间为2024年6月份 新增打印设计功能 导出的默认交互增强以及导入导出模版设计 默认导入导出在交互时可以指定字段 导入导出模版可图形化设计 多模型AI集成设计器器 自定义组件、自定义图表交互友好性增强 自定义组件,属性面板设计模版化,解决设计组件属性面板的时候不知道有哪些默认属性。 增强组件与动作的结合灵活性 组件增加是否有子组件的通用属性,有子组件的组件具备组件拖拽区 增强UX注解能力,原本只有设计器支持的,后端UX注解也进行对应支持 后端低无一体功能开放(原本该功能只在saas版本上提供),方便咱们做应急和简单应用的时,以无代码为主,低代码为辅的模式。通过低无一体可以通过低代码的方式来解决无代码无法支撑的功能。 工作流增强 增加循环审批节点 增加分支汇集节点增强并行流程能力,比如分支汇集节点可以设置:所有并行节点处理完或只要一条处理完就继续执行。

    2024年5月23日
    1.7K00

Leave a Reply

登录后才能评论