美文网首页
给所有代码添加try-catch

给所有代码添加try-catch

作者: 成熟稳重的李先生 | 来源:发表于2021-03-13 01:13 被阅读0次
    const core = require('@babel/core');
    const types = require('babel-types');
    const template = require('@babel/template');
    const sourceCode = `
    function sum(a,b) {
      return a+b+c;
    }
    `;
    
    let tryStatementPlugin = {
        visitor: {
            FunctionDeclaration(nodePath) {
                let { node } = nodePath;
                let { id } = node;
                let nodeStatement = node.body;
                if (nodeStatement && types.isTryStatement(nodeStatement.body[0])) return;
                let catchStatement = template.statement('console.log(error)')();
                let catchClause = types.catchClause(
                    types.identifier('error'),
                    types.blockStatement([catchStatement])
                );
                let tryStatement = types.tryStatement(node.body, catchClause);
                var func = types.functionExpression(
                    id,
                    node.params,
                    types.blockStatement([tryStatement]),
                    node.generator,
                    node.async
                );
                nodePath.replaceWith(func);
            },
        },
    };
    
    const targetCode = core.transform(sourceCode, {
        plugins: [tryStatementPlugin],
    });
    console.log(targetCode.code);
    
    

    相关文章

      网友评论

          本文标题:给所有代码添加try-catch

          本文链接:https://www.haomeiwen.com/subject/bmitcltx.html