美文网首页
给所有代码添加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

  • Kotlin异常处理(2)捕获异常

    try-catch 语句try-catch 表达式多 catch 代码块try-catch 语句嵌套 一、try-...

  • 错误处理与调试

    错误处理 try-catch语句 在使用try-catch时,我们通常是把可能会出错的代码放在try语句块中,把错...

  • svn常用命令

    checkout代码 更新代码 添加新文件到版本库 添加当前目录下所有php文件 递归添加当前目录下的所有新文件 ...

  • ★38.HTTPS

    流程图 前言 以下代码需要catch一堆异常,使用try-catch所有的异常并打印即可。 可以使用工具类。 1....

  • 清除浮动

    HTML代码结构: CSS代码样式: 方法一:给浮动的元素添加兄弟元素,并且给兄弟元素添加clear:bothHT...

  • tab切换案例

    最终效果如下: html布局如下: js实现代码: 具体切换的js代码写法有多种方法一:提前给所有li添加属性(显...

  • 代码设置阴影

    添加阴影方式有很多种,如xml设置,java代码给view设置,或者纯绘制. 通过代码给textview添加红色阴...

  • IOS(swift) 11 UITableView 顶部间距 缝

    在viewDidLoad()中添加代码所有tableview 指定tableview

  • iOS 手势

    本文介绍iOS开发中手势的运用,话不多说,先上代码;给tableView添加长按手势代码如下: 给cell添加长按...

网友评论

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

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