【node】assert 断言

2019-07-10  本文已影响0人  大Q本Q

引入assert

const assert = require('assert')

创建错误消息 AssertionError

调用:

interface O{
    message<string>
    actual<any>,
    expected<any>,
    operator<string>,
    stackStartFn
}
new asset.AssertionError(options:O)

手动创建

// 创建
let message = new assert.AssertionError({
    actual:1,
    expected:2,
    operator:'strictEqual'
})
console.log(message);

/* 输出:
{ AssertionError [ERR_ASSERTION]: 1 strictEqual 2
    at new AssertionError (internal/errors.js:83:11)
    at Object.<anonymous> (/STORE/node/hello-world.js:4:15)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
  generatedMessage: true,
  name: 'AssertionError [ERR_ASSERTION]',
  code: 'ERR_ASSERTION',
  actual: 1,
  expected: 2,
  operator: 'strictEqual' }
*/

自动创建

try {
    assert.strictEqual(1,2);  // 程序报错时,自动创建错误
}catch(err){
    console.log(err);
}

/* 输出:
{ AssertionError [ERR_ASSERTION]: 'a' === 'b'
    at Object.<anonymous> (/STORE/node/hello-world.js:5:9)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
  generatedMessage: true,
  name: 'AssertionError [ERR_ASSERTION]',
  code: 'ERR_ASSERTION',
  actual: 'a',
  expected: 'b',
  operator: '===' }
*/
上一篇 下一篇

猜你喜欢

热点阅读