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"
问题:
catch
块不同。如何解决这个问题?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
});