Javascript 使用断言验证函数参数是一种糟糕的做法吗?

Javascript 使用断言验证函数参数是一种糟糕的做法吗?,javascript,node.js,validation,anti-patterns,Javascript,Node.js,Validation,Anti Patterns,我希望验证我得到的参数在一系列情况下是否有效。特别是在生成SQL时,我想验证传递给函数的对象是否与服务器端同步或有效 我想采用的最自然的方法是使用以下方法 var InvalidIdValue = (actual) => return new Error(`Id: ${actual} is invalid. Expected id >= 1`) var InvalidIdType = (actual, expectedType) => return new Error(`Id:

我希望验证我得到的参数在一系列情况下是否有效。特别是在生成SQL时,我想验证传递给函数的对象是否与服务器端同步或有效

我想采用的最自然的方法是使用以下方法

var InvalidIdValue = (actual) => return new Error(`Id: ${actual} is invalid. Expected id >= 1`)
var InvalidIdType = (actual, expectedType) => return new Error(`Id: ${typeof actual} is invalid. Expected ${typeof expectedType}`)

function sync(query, obj) {
    if(typeof obj.id != typeof 1) 
        return InvalidIdValue(obj.id)
    if(obj.id < 1)
        return InvalidIdValue(obj.id, 1)
    // Pull the data from server
}
这两条路线我都不介意,但这样做是一种坏习惯吗?我提出这个问题的原因是因为我认为断言只适用于TDD


谢谢:)

只要您同意将assert作为依赖项,使用assert没有什么问题。从
.ok
运行的代码是一行,用于检查是否提供了真实值。如果falsy,它将调用
.fail
,这将抛出一个包含相关日志信息的错误

编辑:

以下是源代码中的函数
.ok
.fail

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;

.ok似乎还会抛出一个包含相关和可记录信息的错误。.ok和.fail之间是否有特定的用例?
。ok
使用
.fail
内部抛出错误,我将把这两个函数作为我答案的编辑发布。哦,不。哈哈,非常感谢。我不知道它们是否都是白手起家写的
function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;