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

相关推荐

  • 开放平台

    1. 开放介绍 开放平台是将 Oinone 平台内的能力向外开放,如开放商品信息查询接口、发货单查询接口等。 包括开放接口、三方应用管理。 2. 开放接口 管理开放接口信息,基本操作包括:新增、编辑、停用/启用。 2.1. 新增接口 定义API名称,选择业务域、关联模型,方法支持GET/POST/PUT/DELETE,配置接口参数、响应结果等信息。 2.2. 编辑接口 编辑需要填写的内容同新增,不做赘述。 2.3. 停用/启用 新增后为已启用,停用后,API将无法访问,请慎重使用;针对停用的API进行启用。 3. 应用管理 管理开放接口集成的外部应用,基本操作包括:新增、查看密钥、授权调整、停用/启用。 3.1. 新增应用 新增应用时,输入应用名称,选择数据传输加密算法AES密钥或RSA公钥,勾选授权的API接口。 3.2. 停用/启用 新增后为已启用,停用后,应用将无法访问授权的接口,请慎重使用;针对停用的应用可进行启用。 3.3. 查看密钥 点击【查看密钥】,弹窗展示当前 API Secret,支持复制。 3.4. 授权调整 指调整当前应用的授权的API 范围。

    2024年6月20日
    1.6K00
  • 7.3.1 去除资源上传大小限制

    场景说明 全员营销标准软件产品对于视频上传限制为35M,该大小适合管理短视频类的素材。该软件产品的使用方为营销部门,营销部门不仅管理短视频素材,也负责管理电商商品的视频素材、公司团建的素材等,且不少素材的内存都远大于35M。 业务需求:将全员营销中的内容中心扩展成营销部门的内容统一管理中心,管理营销部门工作范围内的所有内容素材,且不受35M的限制。 实战训练 新增一个资源管理页面,替换原来的资源管理,并构建新的上传行为。 Step1 通过界面设计器,设计出必要管理页面 进入界面设计器,应用选择全员营销,模型通过搜索【素材】选择【Gemini素材】,点击添加页面下的直接创建 设置页面标题、模型(自动带上可切换)、业务类型(运营管理后续会扩展其他类型)、视图类型(表格)后点击确认按钮进入【内容中心-新素材管理】设计页面 进入页面设计器,对【内容中心-新素材管理】表格页面进行设计(更多细节介绍,请参考界面设计产品使用手册) a. 左侧为物料区:分为组件、模型。 ⅰ. 【组件】选项卡下为通用物料区,我们可以为页面增加对应布局、字段(如同在模型设计器增加字段)、动作、数据、多媒体等等 ⅱ. 【模型】选项卡下为页面对应模型的自定义字段、系统字段、以及模型已有动作 b. 中间是设计区域 c. 右侧为属性面板,在设计区域选择中组件会显示对应组件的可配置参数 在左侧【模型】选项卡下,分别把系统字段中的【素材名称】、【素材链接】、【素材来源】、【素材类型】、【更新时间】、【创建时间】等字段拖入设计区域的表格区 设置字段在表格中的展示组件,在设计区域切换【素材链接】展示组件为【超链接】 设置字段在表格中的展示组件的属性,在设计区域选中【素材名称】,在右侧属性面板中设置【标题】为【内容名称】 设置字段在表格中的展示组件的属性,在设计区域选中【创建时间】,在右侧属性面板中设置【标题】为【上传时间】 在左侧【模型】选项卡下,把动作分类下的提交类型【下载】和【删除】动作拖入中间设计区的动作区,并选择【删除】按钮,在右侧属性面板中设置【按钮样式】为【次要按钮】 在左侧【组件】选项卡下,把动作分类下的【跳转动作】拖入中间设计区的动作区,并在右侧属性面板中设置动作名称为【上传素材】,数据控制类型为【不进行数据处理】,打开方式为【弹窗打开】,【弹出内容】为【创建新页面】,【弹窗模型】通过搜索【素材】选择【Gemini素材代理-上传】,并点击保存 设计区选中【上传素材】按钮,点击【打开弹窗】设计【素材上传】的操作页面,此时会发现左侧【模型】选项卡下的当前模型切换成了【Gemini素材代理-上传】 a. 分别把系统字段中的【上传素材链接列表】拖入【Gemini素材代理-上传】的弹窗页面设计区。 b. 选中【上传素材链接列表】切换展示组件为【文件上传】 c. 选中【上传素材链接列表】并在右侧属性面板中 ⅰ. 设置【校验】分组下,设置【最大上传文件体积】为空,即不设置 ⅱ. 设置【校验】分组下,设置【限制上传文件类型】为打开,并勾选【图片】和【视频】 ⅲ. 设置【交互】分组下的宽度属性为【1】 在左侧【模型】选项卡下,把动作分类下的提交类型【上传素材】动作拖入中间设计区的动作区 在左侧【组件】选项卡下,把动作分类下的【客户端动作】类型拖入中间设计区的动作区,选中并在右侧属性面板中设置【动作名称】为返回,设置【客户端行为】为【关闭弹窗】,点击【保存】按钮来完成动作的基础设置 选中【返回】按钮、并在右侧属性面板中设置【按钮样式】为【次要按钮】 关闭弹窗返回主模型设计区 点击右上角【显示母版】进入页面最终展示形式,点击添加菜单项,并在输入框中输入【新内容中心】 点击菜单右侧设置图标,选择【绑定已有页面】,进行菜单与页面的绑定操作 在绑定页面中,模型选择【Gemini素材】,视图选择【内容中心-新素材管理】,点击确认按钮提交 最后别忘了点击右上角【发布】按钮对【内容中心-新素材管理】表格页面进行发布,回到界面设计器首页查看刚刚建好的表格页面 Step2 测试完成以后隐藏原【内容中心】菜单 进入【界面设计器】管理页面,通过点击【设计图标】进入任一页面的设计页面 点击右上角【显示母版】进入页面最终展示形式,找菜单【内容中心】点击菜单右侧设置图标,选择【隐藏菜单】,因为【内容中心】菜单是标准产品自带菜单,只能进行隐藏操作,无法进行如绑定页面和调整菜单顺序 Step3 回到全员营销应用,刷新页面体验效果 整个实战训练就到此结束,更多细节请参阅具体的产品使用手册

    2024年5月23日
    84400
  • 节点动作

    节点动作为触发和结束结点中间的动作,点击节点名称可以进行修改。

Leave a Reply

登录后才能评论