Node.js – util.types.isNativeError() 方法
所述util.types.isNativeError()方法检查传递的值是否是一个内置的错误类型或没有。如果满足上述条件,则返回True,否则返回False。错误可以是任何类型。
语法
util.types.isNativeError(value)
参数
它需要一个参数-
value-此输入值接受所需参数的输入并检查它是否是错误类型。
它根据传递的输入值返回True或False。
示例1
创建一个名为“isNativeError.js”的文件并复制以下代码片段。创建文件后,使用命令“nodeisNativeError.js”运行此代码。
//util.types.isNativeError()演示示例 //导入util模块 const util = require('util'); //将新的错误实例传递给输入参数 console.log("1." + util.types.isNativeError(new Error())); //将TypeError传递给输入参数 console.log("2." + util.types.isNativeError(new TypeError())); //将RangeError传递给输入参数 console.log("3." + util.types.isNativeError(new RangeError()));输出结果
C:\home\node>> node isNativeError.js 1.true 2.true 3.true
示例2
让我们再看一个例子
// Importing the util & assert module const util = require('util'); const assert = require('assert'); function fun() { return new Error('Some Unknown Error occured') } function fun1() { return (5/0); //将返回无穷 } //传递从函数返回的新错误 console.log("1." + util.types.isNativeError(fun())); //传递数学错误 console.log("2." + util.types.isNativeError(fun1())); //将AssertionError传递给输入参数 console.log("3." + util.types.isNativeError(assert.AssertionError));输出结果
C:\home\node>> node isNativeError.js 1.true 2.false 3.false