01day-assert 断言

77 阅读1分钟

首次真正系统性学习 node ,特此记录自己一点点心得。
关于 assert 断言,我这边就按照文档并结合自己的源码理解,照本宣科一波。

类 assert.AssertionError

关于这个 Class ,它是继承于 Error,作用是作为最后的默认异常抛出,针对所有的断言结果。
源码案例如下:

image.png

image.png

image.png
关于 AssertionError 中的 validateObject 函数,目前看来只是对数据的处理及校验。从上我们可以得出几点结论:

  • 同时从 innerFail 函数得知为什么当断言的 message 是 Error 时,为什么会直接抛出而不抛出默认 AssertionError。
  • 当然,从源码得知并不是所有的 api 都是用 innerFail 的函数,但是会以其他逻辑遵从文档所表述结果。
  • 同时上述截图也解释了为什么当 meassge 为 string 时会作为 AssertionError 的提示消息返回。
  • 当参数不够是则会直接抛出另外的异常

方法 api

只是为了让本人的记忆更牢固才写

assert(value[, meassge])

官方文档描述:

  • value 检查是否为真的输入
  • meaasge 异常提示或者自定义异常

源码截图

image.png

image.png

image.png 前提: value 为假时抛出异常

  • 当没有参数传入时,message 为 No value argument passed to assert.ok()
  • 当没有 message 传入时,message 为默认获取的表达式
  • 当有 meassge 传入时,且 meassage 为字符串,则异常 message 为传入值
  • 当有 meassge 传入时,且 meassage 为Error,则直接抛出自定义异常

后续 api 我就不加以赘述了,忘了可以多看看文档