如何在AJV代码生成中创建try-catch块?

问题描述 投票:0回答:1
Node.js v18.16.0
"ajv": "^8.11.0",

当我尝试编译这个时:

ajv.addKeyword("isEven", {
  type: "number", // Applies to numbers
  code(cxt) {
    const { data, schema } = cxt;

    // Wrap validation code in a try-catch block
    cxt.gen.block(() => {
      cxt.gen
        .try(() => {
          if (schema === true) {
            // If schema is true, fail if the number is odd
            cxt.fail(_`${data} % 2 !== 0`);
          } else if (schema === false) {
            // If schema is false, always pass validation
            cxt.pass();
          } else {
            // Invalid schema value, throw an error
            throw new Error("'isEven' schema must be a boolean");
          }
        })
        .catch((e) => {
          // Handle runtime errors gracefully
          cxt.fail(_`"Validation error in 'isEven': " + ${e.message}`);
        });
    });
  },
  errors: true, // Enable custom error messages
});

我收到此错误:

Error: CodeGen: "try" without "catch" and "finally"

问题:

  1. 所以我认为我的语法可能与我需要如何实现
    catch
    块不同。如何解决这个问题?
  2. 哪里有关于如何使用AJV代码生成的官方文档?
javascript node.js npm ajv
1个回答
0
投票

https://ajv.js.org不支持try/catch所以必须像这样删除

ajv.addKeyword("isEven", {
  type: "number", // Applies to numbers
  code(cxt) {
    const { data, schema } = cxt;

    if (schema === true) {
      // If schema is true, fail if the number is odd
      cxt.fail(_`${data} % 2 !== 0`);
    } else if (schema === false) {
      // If schema is false, always pass validation
      cxt.pass();
    } else {
      // Invalid schema value, throw an error
      throw new Error("'isEven' schema must be a boolean");
    }
  },
  errors: true, // Enable custom error messages
});
© www.soinside.com 2019 - 2024. All rights reserved.