1.0.8 • Published 1 year ago

no-catch-loader v1.0.8

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

no-catch-loader

它是一个 webpack 的 loader ,帮助你在使用 async-await进行异步编程时自动添加catchfinally语句块。提供一种全局捕获异步错误的方式,可用于 JS 错误统一处理、上报;也可实现自定义的错误处理。

Getting Started

To begin, you'll need to install no-catch-loader:

npm install --save-dev no-catch-loader

or

yarn add -D no-catch-loader

or

pnpm add -D no-catch-loader

Then add the plugin to your webpack config. For example:

Example

vue.config1.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: "no-catch-loader",
            // 没有特殊要求可不配置
            options: {},
          },
        ],
      },
    ],
  },
}

demo.js

async defaultTest() {
  // getFn是一个不存在的函数
  await getFu()
},

经过loader转换后的代码如下:

async defaultTest() {
  try {
      // getFn是一个不存在的函数
      await getFu();
  } catch (error) {
      console.log(error);
  }
},

vue.config2.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: "no-catch-loader",
            // 没有特殊要求可不配置
            options: {
              catchCode: (identifier) => `
                // catchFn 是用户可以自定义的函数。可实现局部自定义错误捕获
                if(catchFn) {
                  catchFn()
                }else {
                  // 可使用函数作用域内的一些方法
                  this.$message('catch');
                  console.log(${identifier})
                }
              `,
              identifier: "e",
              finallyCode: `
                console.log("finally")  
              `,
            },
          },
        ],
      },
    ],
  },
}

demo.js

async defaultTest() {
  // getFn是一个不存在的函数
  await getFu()
},

经过loader转换后的代码如下

async defaultTest() {
  try {
      // getFn是一个不存在的函数
      await getFu();
  } catch (e) {
      if (catchFn) {
          catchFn();
      } else {
          this.$message('catch');
          console.log(e);
      }
  } finally {
      console.log("finally");
  }
}

Options

选项类型默认值可选值描述
catchCodeFunction(identifier) => console.log(${identifier})需要添加的 catch 执行函数,更改模板字符串的内容即可,模板内容为可执行的 JS 语句
identifierStringerrorcatch 语句块中 参数变量标识符
finallyCodeString模板字符串,内容是可执行的 JS 语句
1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago