MERN 堆栈 err.kind 表达式:它来自哪里?

MERN stack err.kind expression: Where does it come from?

我最近正在尝试进行 MERN 堆栈开发,我在一个教程中看到了一个错误处理表达式,用于识别抛出的错误类型。据我目前所见,可以使用以下表达式,而且它们似乎使用的是标准 js 库。

err.name === "example"
err.message.indexOf('Cast to ObjectId failed') !== -1
err.message instanceof mongoose.Error.CastError

但是后来我看到了这种处理错误的方式,就是使用了“error.kind”属性。我四处寻找它的来源以及我应该期望它具有什么样的价值,但没有成功。

希望您能解答以下问题:

我显然在这个阶段仍然感到困惑,很高兴阅读您推荐的任何阅读材料material。

router.get('/user/:user_id',async (req,res)=>{

    try {
        const profile = await Profile.findOne({user:req.params.user_id}).populate('User',['name','avatar']);
        


    if(!profile){
        return res.status(400).json({msg:'There is no profile for the user'});
    }

    res.json(profile);

    } catch (err) {

        console.log(err.message);
        
        if(err.kind == 'ObjectId'){
            return res.status(400).json({msg:'There is no profile for the user'});
        }

        res.status(500).json({msg:'Server Error'});
    }

});

想通了!现在我对不同的 JS 组件如何在 MERN 堆栈中工作有了更多的了解。

“种类”是 属性 内部的 CastError 和 ValidationError,根据使用 Mongoose 包时发生的错误抛出。

在迁移到 Mongoose v4 之前,使用“类型”属性 来识别发生的 CastError 或 ValidationError 的类型。但是,这与内部使用 Error.type 属性 的 V8 JavaScript 引擎冲突。

仍然没有在 Mongoose 文档中找到太多关于我们可以从“种类”属性 获得什么样的可能值的信息,但至少我们知道它来自哪里以及下面的发行说明解释它的制作原因。

https://mongoosejs.com/docs/migration.html#casterror-and-validationerror-now-use-kind-instead-of-type-to-report-error-types