node.js - 在 Nodejs 中使用断言模块设置 errorType 标志
问题描述
我喜欢Nodejs的assert模块。
我大量使用以下语法。
var assert = require('assert')
var l = [1, 2, 3]
var x = 2
assert(l.indexOf(x) < 0, "you are in list blacklisted numbers")
在这段代码中,如果x
是 3,那么我会看到它被列入黑名单的错误。所以我想将 errorType 设置为某个值。如何使用断言模块来做到这一点?目前我正在使用if/else
if (!(l.indexOf(x) < 0)) {
var errorType = 1
assert(false, "you are in list blacklisted numbers")
}
解决方案
一种方法是创建这样的自定义错误
var assert = require('assert')
class ErrorType extends Error {
constructor(message, code) {
super(message)
this.name = this.constructor.name
this.code = code
Error.captureStackTrace(this, this.constructor)
}
}
try {
var l = [1, 2, 3]
var x = 2
assert(l.indexOf(x) < 0, new ErrorType("you are in list blacklisted numbers", 1234))
} catch (error) {
if (error instanceof ErrorType) {
console.log(error)
} else {
console.log("normal error")
}
}
推荐阅读
- javascript - 当我提交用户登录表单时,我希望我的网页被重定向
- reactjs - 如何在不重新启动循环的情况下读取连续异步循环内的反应上下文/状态数据
- amazon-web-services - AWS SSL 证书安装问题
- linux - ELF 文件中的重定位加数 - Elf64_Rel 与 Elf64_Rela?
- javascript - 如何在reactjs中反转无限滚动条
- python - 使用 pyserial 读取 Scale 显示 b''
- json - SpringBoot 使用 PUT 映射创建/更新资源
- python - GridSearchCV 估计我的模型很慢
- sqlite - 不再支持 react-native-sqlite-storage android.useDeprecatedNdk NdkCompile
- java - 使用 JavaFX 未出现图像,如何调用它