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.2 Oinone以模块为组织

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

    Oinone 7天入门到精通 2024年5月23日
    1.5K00
  • 数据类

    1.数据类 1.1 新增数据 新增数据节点可以为任意模型通过表达式新增数据,包含两种模式,「节点执行完即增加业务数据」功能下新增的数据也可以同步触发流程,相反「节点执行完不增加业务数据」则不会触发新增业务数据关联的流程,数据仅可用于后续流程使用。 流程增加的数据在节点执行时就生效。 1.2 更新数据 更新数据节点可以为任意模型通过表达式更新数据。 1.3 获取数据 当流程需要调用触发模型之外的模型中的数据时就需要使用获取数据的功能。 需要选择获取单条/多条数据,选择一个获取数据的模型,可以设置一些筛选项减少不必要的数据。最后需要设置未获取到数据时的执行方式。 继续执行:跳过本次数据获取,继续执行流程。 向模型中新增数据后继续执行:新增数据来供后续节点使用,新增数据同时存入数据库中。 终止流程:终止流程将结束该流程,不管之后是否还有流程节点。 1.4 删除数据 删除数据节点可以将流程节点上面的模型数据从数据库中删除。 1.5 更新流程参数 可以将「流程配置」中的「流程参数」进行修改,仅有变更过的流程参数才能其他节点选中。 1.6 引用逻辑 可以在流程中使用模块自带的逻辑或使用低代码设计的逻辑。

    2024年5月23日
    94200
  • 4.5.1 研发辅助之插件-结构性代码

    研发辅助意在 消灭研发过程中的重复性工作提升研发效率,如结构性代码 提供生产示例性代码,如果根据模型生成导入导出、view自定义配置等经常性开发 一、插件安装 根据自身Idea版本下载插件并安装: 版本 插件 2023.1 pamirs-source-maker-1.0.0-2023.1.zip(2.4 MB) 2021.1 pamirs-source-maker-1.0.0-2021.1.zip(2.4 MB) 2021.2 pamirs-source-maker-1.0.0-2021.2.zip(2.4 MB) 2021.3 pamirs-source-maker-1.0.0-2021.3.zip(2.4 MB) 2022.1 pamirs-source-maker-1.0.0-2022.1.zip(2.4 MB) pamirs-source-maker-1.0.0-223-EAP-SNAPSHOT(2.4 MB) 表4-5-1-1 插件列表 二、研发辅助之配置式结构性代码生成器 我们在开发过程中为了日后代码易于维护和修改,往往会做工程性的职责划分。 除去模型外会有 代理模型和代理模型Action来负责前端交互 以面向接口的形式来定义函数,就会有api和实现类之分 如果项目有多端,那么如代理模型和代理模型Action又要为每一个端构建一份 在大型项目的初始阶段,我们需要手工重复做很多事情,特别麻烦。现在用oinone的研发辅助插件的结构性代码生成器,就可以避免前面的重复工作 插件执行的配置文件 <?xml version="1.0" encoding="utf-8" ?> <oinone> <makers> <!– 根据模型生成代理类、代理类的Action、Service、ServiceImpl –> <maker> <!– 选择模型所在位置 –> <modelPath>/Users/oinone/Documents/oinone/demo/pamirs-second/pamirs-second-api/src/main/java/pro/shushi/pamirs/second/api/model</modelPath> <!– 代理模型、代理模型Action生成相关配置信息 –> <proxyModules> <module> <!– 代理模型和代理模型Action的生成位置信息 –> <generatePath>/Users/oinone/Documents/oinone/demo/pamirs-second/pamirs-second-api/src/main/java/pro/shushi/pamirs/second/api</generatePath> <!– 代理模型和代理模型Action的模块前缀 –> <modulePrefix>second</modulePrefix> <!– 代理模型和代理模型Action的模块名,代理模型和代理模型Action类名为moduleName+模型名+"Proxy"+"Action" –> <moduleName>second</moduleName> <!– 代理模型和代理模型Action的包名,实际包名为 packageName+".proxy"或packageName+".action"–> <packageName>pro.shushi.pamirs.second.api</packageName> </module> </proxyModules> <!– 根据模型生成api,包括service(写方法)和queryService(读方法) –> <apiModule> <!– service和queryService的生成位置信息 –> <generatePath>/Users/oinone/Documents/oinone/demo/pamirs-second/pamirs-second-api/src/main/java/pro/shushi/pamirs/second/api</generatePath> <!– service和queryService的模块前缀 –> <modulePrefix>second</modulePrefix> <!– service和queryService的模块名 –> <moduleName>second</moduleName> <!– service和queryService的包名,实际包名为 packageName+".service" –> <packageName>pro.shushi.pamirs.second.api</packageName> </apiModule> <!– 根据模型生成api实现类,包括serviceImpl(写方法)和queryServiceImpl(读方法) –> <coreModule> <!– serviceImpl和queryServiceImpl的生成位置信息 –> <generatePath>/Users/oinone/Documents/oinone/demo/pamirs-second/pamirs-second-core/src/main/java/pro/shushi/pamirs/second/core</generatePath> <!– serviceImpl和queryServiceImpl的模块前缀 –> <modulePrefix>second</modulePrefix> <!– serviceImpl和queryServiceImpl的模块名 –> <moduleName>second</moduleName> <!– serviceImpl和queryServiceImpl的包名,实际包名为 packageName+".service" –> <packageName>pro.shushi.pamirs.second.core</packageName> </coreModule> </maker> </makers> </oinone> 图4-5-1-1 插件执行的配置文件 三、研发辅助之多模型结构性代码生成器 是配置式结构性代码生成器的补充,应对开发后期维护中新增模型的场景。它的不同点在于只要选择模型文件就可以,不需要专门编写xml文件。生成的文件默认就在模型所在路径下 Step1 菜单栏上找到oinone,并点击子菜单【多模型结构性代码生成器】 图4-5-1-2 多模型结构性代码生成操作步骤一 Step2 设置必要的信息 模型前缀 模型的所属模块 代理模型的模块 这三个信息分别用于构建 代理模型的MODEL_MODEL = 模型前缀.代理模型的模块.代理模型类名 服务的FUN_NAMESPACE = 模型前缀.代理模型的模块.服务类名 图4-5-1-3 多模型结构性代码生成操作步骤二 Step3 选择为哪些模型生成对应的结构性代码 图4-5-1-4 多模型结构性代码生成操作步骤三 Step4 代码在模型所在目录 生成的文件默认就在模型所在路径下,您可以手动拖动到对应的包路径当中去 图4-5-1-5 多模型结构性代码生成操作步骤四

    2024年5月23日
    96400
  • 企业个性化配置

    平台除了帮助企业快速解决业务需求外,还提供了企业文化、风格个性化能力,本章节详细介绍个性化配置。包括:登陆页配置、企业形象配置、系统风格配置。 系统配置 配置入口 配置入口:右上角登陆账号——系统配置——全局配置——登陆页配置、企业形象配置、系统风格配置。 登陆页配置 用户自定义登陆页的主题,一共有六个主题可选择,分别为: 图一:左侧是图片,右侧是登录输入框,Logo在左上角; 图二:右左侧是图片,右侧是登录输入框,Logo在左上角; 图三:底图是图片,登录输入框浮在页面左侧,Logo在左上角; 图四:底图是图片,登录输入框浮在页面中间,Logo在左上角; 图五:底图是图片,登录输入框浮在页面右侧,Logo在左上角; 图六:底图是图片,登录输入框浮在页面中间,Logo在登录框上方。 页面背景 上传登录页背景,支持上传jpg、png格式的图片或mp4、mov、avi格式视频。尺寸建议为1920*1080px,文件大小不超过50MB。 登录页logo:指配置登录页左上角的logo图标。 预览:配置后可在右侧电脑中点击全屏预览效果。 配置示例 企业形象配置 企业形象配置:可设置企业信息、业务应用导航栏logo、浏览器logo,设置完成之后,点击发布之后设置生效。 系统风格配置 系统风格配置,可设置主题(浅色、深色)、尺寸(大、中、小),配置后可全屏预览,发布后即可更换成对应的风格。 下载代码可进行自定义风格。

    2024年6月20日
    99700
  • 流程设计

    1.流程设计 进入流程设计页之后可以进行流程名称、流程说明的编辑,可以进行流程设计,流程参数配置,保存和发布。 1.1 流程配置 点击进入流程配置页面,若需要配置一些参数供流程使用,可在此添加和删除。删除流程参数时,若该参数已在流程中被使用则无法删除。参数支持文本、数值、日期、布尔四种类型。 1.2 保存 点击后流程设计进行存档,流程设计不完整也支持保存,下次进入流程设计回到保存的页面。 1.3 发布 第一次发布时右上角发布显示文字为发布流程,后续发布按钮显示文字为更新发布。发布后流程才会按照设计触发,首次发布和更新发布的逻辑一致,若流程中有未解决的错误则无法发布不成功,发布成功后页面跳转到显示全部流程的页面,流程状态为已启用、已更新。

    2024年6月20日
    91900

Leave a Reply

登录后才能评论