All Products
Search
Document Center

Quick Tracking:JS Exception Capture Interpolation Tool

Last Updated:Mar 26, 2025

I. Function Introduction

Js is a single-threaded weak-type scripting language, so many errors will be discovered at the time of running. Once a run time error occurs, the entire js thread will hang up, resulting in our page not responding. Therefore, we need to have a bottom-up method to avoid it, and actively trycatch run time expressions that may produce errors is the easiest way to implement it. The tool provided in this article is to insert the API of Web or applet SDK error reporting into the Catch expression by building automation, and provide a tool run time collecting exception stack. It is a supplement to the current APM WEB /applet SDK error collection (onerror、unhandledrejection ....).

II. Quick start

Note

Tip: Before using the tool to participate in the construction, be sure to ensure that the SDK instrumentation tool that has integrated Quick Tracking WEB(v2.0.7 and above support) or applets (v1.0.4 and above) will insert the SDK error active reporting API into the Catch expression as a function expression, so be sure that the Quick Tracking SDK is loaded before the Catch callback is executed when an exception occurs at runtime. (By the way, even if the execution order is reversed, the inserted code has made a logical bottom to avoid errors.)

// babel
npm install -D @umengfe/babel-plugin-uapm-trycatch
// rollup
npm install -D @umengfe/rollup-plugin-uapm-trycatch

.

{
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
  plugins: [
    '@babel/plugin-transform-runtime',
+    [
+      @umengfe/babel-plugin-uapm-trycatch,
+      {
+        include: ['**/*.tsx', '**/*.ts'],
+        platform: 'wechat'
+      }
+    ]
  ],
};
const webpack = {
  entry: resolve('src/main.tsx'),
  module: {
    rules: [
      {
        test: /\.jsx?|tsx?$/,
        exclude: /node_modules/,
        use: [
          'babel-loader',
        ],
      },
    ],
  },
  ...
};
"scripts": 
    "build": "webpack --progress --env=production --config ./build/webpack.prod.js --profile",
},
// npm run build

image.png

// The example of the target peg.
const Index = () => {
   try {
    throw new Error("An error occurred")
  } catch (error) {
     // Before the pile is inserted
    console.log(error);
  }
  return (
    <Page>
      <GuidePage config={config} />
    </Page>
  );
};

III. Description of input parameters

Parameter

Required

Parameters

Type

Example

include

No

Included files and path rules

string[]

include: ['/*.tsx', '/*.ts']

exclude

No

Excluded files and path rules

string[]

exclude: ['**/node_modules']

platform

No

Supported platform types (wechat, WEB/H5, alipay)

string

platform: 'web | alipay | wechat'

The target build platform can also be specified in the build command of the package.json by using the agreed environment variable (UAPM_PLATFORM) with the build command. At the same time, the value priority configuration parameter is higher than the environment variable.

{
  "name": "",
  "version": "0.0.1",
  "scripts": {
    "build:web": "cross-env UAPM_PLATFORM=web npm run build",
    "build:wechat": "cross-env UAPM_PLATFORM=wechat npm run build"
    "build:alipay": "cross-env UAPM_PLATFORM=alipay npm run build"
  }
}

IV. Support Situdation

O1CN01OHcOHv1n3ADopGWLI_!!6000000005033-0-tps-1284-332

V. Principle Analysis

Adding code to static code requires traversing the expression type of all the code in the file, so AST is a best choice. With the help of compiler tools (Babel, Rollup) to parse the AST syntax tree and participate in the construction, we can specify a certain type of expression to modify it or add properties and expressions when traversing, so as to achieve the most basic code insertion. For further improvement, we need to consider avoiding the execution dead loop caused by SDK self-interpolation, avoiding repeated interpolation judgment, designing the blacklist and allow list files or path parameters for interpolation, and considering supporting multiple types of JavaScript compilers on the market.

  • In the following figure, ① is a conditional filter JS捕捉截图.jpeg

6. More integration cases

6.1 Remax

1) Execute the command in the terminal to install the necessary npm package.

npm install @umengfe/mini-apm -S
npm install babel-preset-remax -D
npm install @umengfe/babel-plugin-uapm-trycatch -D 

2) Modify the commands in package.json to add UAPM_PLATFORM=wecha.

"build": "cross-env UAPM_PLATFORM=wechat NODE_ENV=production remax build -t"

3) Integrate APM Mini SDK in app.js.

const { init } = require('@umengfe/mini-apm');

init({
  appKey: 'xxxx',
  debug: true,
});

4) Add the stump plug-in in the babel.config.js.

module.exports = {
    plugins: [
        ['@umengfe/babel-plugin-uapm-trycatch', {
            exclude: ['**/node_modules'],
            platform: 'wechat'
        }]
    ],
    presets: [
      [
        'remax',{},'babel-preset-remax'
      ],
    ],
};

5) Create a new error in src/pages/index/index.js for testing.

// Create an error in src/pages/index/index.js for testing.
const errorButton = () => {
	try {
    throw new Error('Remax frame stub test error');
  } catch (e) {
    console.log(e);
  }
}

export default () => {
  return (
    <View className={styles.app}>
      <View className={styles.header}>
        <View className={styles.text}>
          <Button onClick={errorButton}> Test Error Button </Button>
        </View>
      </View>
    </View>
  );
};

6.2 Taro3

1) Execute the command in the terminal to install the necessary npm package.

npm install cross-env -D
npm install @umengfe/mini-apm -S
npm install @umengfe/babel-plugin-uapm-trycatch -D

2) Modify the commands in package.json to add UAPM_PLATFORM=wechat and UAPM_PLATFORM=alipay.

"build": "cross-env UAPM_PLATFORM=wechat taro build --type weapp && cross-env UAPM_PLATFORM=alipay taro build --type alipay"

3) Integrate APM Mini SDK in app.ts

import Taro from '@tarojs/taro';

if(Taro.ENV_TYPE.WEAPP) {
  const { init } = require('./utils/wx.cjs')

  init({
    appKey: 'xxxx',
    debug: true
  })
} else if (Taro.ENV_TYPE.ALIPAY) {
  const { init } = require('./utils/alipay.cjs')

  init({
    appKey: 'xxxx',
    debug: true
  })
}

4) Add the plug-in declaration in the babel.config.js and add the introduction of the instrumentation tool in the plugins

const plugins = []
plugins.push([
  '@umengfe/babel-plugin-uapm-trycatch',
  {
    exclude: ['**/node_modules'],
    platform: 'wechat'
  }
])
module.exports = {
  presets: [
    ['taro', {
      framework: 'react',
      ts: true
    }]
  ],
  plugins
}

5) Test in index.tsx

errorButton = () => {
    try {
      throw new Error ('Platform:${Taro.getEnv()}, Error message: Custom error, Version:Taro3')
    } catch (error) {
      console.log(error);
    }
  }

  render () {
    return (
      <div className='index'>
        <Button onClick={this.errorButton}> Custom Error Button </Button>
      </div>
    )
  }

6.3 Uniapp

1) Execute the command in the terminal to install the necessary npm package.

npm install @umengfe/mini-apm -S
npm install @umengfe/babel-plugin-uapm-trycatch -D 

2) Modify the package.json commands, according to different compilation platform to add different compilation parameters UAPM_PLATFORM=web, UAPM_PLATFORM=wechat, UAPM_PLATFORM=alipay.

"build": "cross-env UAPM_PLATFORM=web npm run build:h5",
"build:mp-weixin": "cross-env UAPM_PLATFORM=wechat UNI_PLATFORM=mp-weixin NODE_ENV=production vue-cli-service uni-build",
"build:mp-alipay": "cross-env UAPM_PLATFORM=alipay UNI_PLATFORM=mp-alipay NODE_ENV=production vue-cli-service uni-build",

3) Integrate APM Mini SDK in main.ts

/* #ifdef MP-WEIXIN */
import { init } from './utils/wx.esm.js';

init({
    appKey: 'xxxx',
    debug: true
})
/* #endif */

/* #ifdef MP-ALIPAY */
import { init } from './utils/alipay.esm.js';

init({
    appKey: 'xxxx',
    debug: true
})

4) Add the plug-in declaration in the babel.config.js and add the introduction of the instrumentation tool in the plugins

plugins.push([
	'@umengfe/babel-plugin-uapm-trycatch',
	{
		exclude: ['**/node_modules'],
		platform: 'wechat || alipay || web'
	}
])

5) Test in index.vue

<template>
	<view class="content">
		<view>
      <button
				open-type=""
				hover-class="button-hover"
				@click="testButton"
			>
				Custom Error Button
			</button>
    </view>
	</view>
</template>


methods: {
	testButton() {
		try {
			throw new Error(`"platform": ${process.env.UNI_PLATFORM}, "frame": "uni-app", "message": "This is test error"`)
		} catch (error) {
			console.error(error)
		}
	},
}

6.4 Vue3 + Vite

1) Execute the command in the terminal to install the necessary npm package.

npm install @umengfe/apm -S // web sdk
npm install @umengfe/rollup-plugin-uapm-trycatch -D

2) Modify the commands in package.json to add UAPM_PLATFORM=web.

"build": "cross-env UAPM_PLATFORM=web run-p type-check build-only"

3) Integrate APM Mini SDK in main.ts

import { init } from '@umengfe/apm';
init({
    pid: 'xxxx',
    logLevel: 3,
    blankConfig: {
        blank_target: '',
        blank_timeout: 0,
        screenshot: undefined,
        X: 0,
        Y: 0
    },
    xhrConfig: {
        enableReqBody: true
    },
    fetchConfig: {
        enableReqBody: true
    }
})

4) Add the plug-in declaration in the vite.config.js and add the introduction of the instrumentation tool in the plugins

import tryCatchPlugin from '@umengfe/rollup-plugin-uapm-trycatch'

tryCatchPlugin({
      exclude: [
        'node_modules/**',
        'utils/**'
      ],
      include: [
        '*.js',
        '**/*.js',
        '*.ts',
        '**/*.ts',
        '*.vue',
        '**/*.vue'
      ]
})

5) Test in index.vue

function testButton() {
	try {
		throw new Error('vite test')
	} catch (error) {
		console.error(error)
	}
}

<template>
  <header>
    <img
      alt="Vue logo"
      class="logo"
      src="@/assets/logo.svg"
      width="125"
      height="125"
    />

    <button open-type="" hover-class="button-hover" @click="test">
      Custom event
    </button>
  </header>

  <RouterView />
</template>

6.5 React + Webpack

1) Execute the command in the terminal to install the necessary npm package.

npm install @umengfe/apm -S
npm install @umengfe/babel-plugin-uapm-trycatch -D

2) Modify the commands in package.json to add UAPM_PLATFORM=web.

"build": "cross-env UAPM_PLATFORM=web npm run build"

3) Integrate APM Mini SDK in main.ts

import { init } from '@umengfe/apm';
init({
    pid: 'xxxx',
    logLevel: 3,
    blankConfig: {
        blank_target: '',
        blank_timeout: 0,
        screenshot: undefined,
        X: 0,
        Y: 0
    },
    xhrConfig: {
        enableReqBody: true
    },
    fetchConfig: {
        enableReqBody: true
    }
})

4) Add plug-in declaration in. babelrc.js and add the introduction of instrumentation tools in plugins

const path = require('path');
module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-typescript',
    
  ],
  plugins: [
    '@umengfe/babel-plugin-uapm-trycatch',
    [
      "uapm-trycatch",
      {
        include: ['**/*.tsx', '**/*.ts']
      }
    ]
  ],
};