首页 > 解决方案 > 在 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")
}

标签: node.jserror-handlingassert

解决方案


一种方法是创建这样的自定义错误

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")
    }
}

推荐阅读