Node.js 中的 assert.ifError() 函数
node.jsjavascriptweb developmentfront end technology
assert 模块提供了一系列用于函数断言的不同功能。 Assert.ifError() 函数提供了一种功能,如果值不为 null 或 undefined,则抛出错误。如果值不是其中两个,则会抛出错误。
语法
assert.ifError(value)
参数
上述参数描述如下 −
value ——此参数将保存要检查错误的值。除了值为 'null' 的情况外,它将在所有情况下抛出错误或 'undefined'。
安装 Assert 模块
npm install assert
assert 模块是内置的 Node.js 模块,因此您也可以跳过此步骤。您可以使用以下命令检查 assert 版本以获取最新的 assert 模块。
npm version assert
在您的函数中导入模块
const assert = require("assert").strict;
示例
创建一个名为 – assertIfError.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码。
node assertIfError.js
assertIfError.js
// 导入模块 const assert = require('assert').strict; try { assert.ifError('6'); // Will throw an error: value: 6 } catch(error) { console.log("Error:", error) }
输出
C:\home
ode>> node assertIfError.js Error: { AssertionError [ERR_ASSERTION]: ifError got unwanted exception: '6' at Object. (/home/node/mysql-test/assert.js:5:9) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) generatedMessage: false, name: 'AssertionError [ERR_ASSERTION]', code: 'ERR_ASSERTION', actual: '6', expected: null, operator: 'ifError' }
我们可以在上面的例子中看到该值不为 null 或 undefined。
示例
我们再看一个例子。
// 导入模块 const assert = require('assert').strict; try { assert.ifError(null); console.log("No Error occured") assert.ifError(undefined); console.log("OK") // Value: undefined & null is valid } catch(error) { console.log("Error:", error) }
输出
C:\home
ode>> node assertIfError.js No Error occured OK
我们可以在上面的例子中看到,值为 null 和 undefined,它们是 assert 中 ifError 的有效值。