node.js - 在 throw new Error('record not found') 语句中出现 Nodejs 和 Mongoose 错误
问题描述
我正在使用 mongoose 中间件运行 Reactjs+Nodejs 和 Mongodb 连接。我有一个查找输入商家 ID 是否存在的声明。如果商家 id 存在,则代码可以正常工作,但是当找不到商家 id 时,我正在尝试发送错误文本以响应 js。Nodesjs 中的控件在语句 throw new Error('record not found') 抛出错误时失败。
请在下面找到我的代码。
const jwt = require('jsonwebtoken')
const Merchant = require('../models/merchant')
const auth = async (req, res, next) => {
try{
const merchantid = await Merchant.findOne({merchantid: req.body.merchantid }) // grab user from database
if (!merchantid) {
throw new Error('record not found')
}
req.merchantid = merchantid
next()
} catch (e) {
res.status(401).send(e)
}
}
module.exports = auth
请找到我在第 8 行收到的错误消息(抛出新错误('找不到记录'))。
Error: record not found
at auth (C:\Users\Poorna\Desktop\New_folder\Projects\react\React_new_App\temple_receipt_app\server\middleware\auth.js:8:10)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
提前致谢。
解决方案
这就是 throw 的工作原理。你想像这样返回调用系统
改变
throw new Error('record not found')
至
res.status(404)
推荐阅读
- tfs - 将集合从 TFS 2015 迁移到 TFS 2018
- c# - 通过 sender 参数访问后台工作程序
- python - 比较 2 个 CSV 文件并将一个文件中的值添加到另一个匹配项
- oxyplot - Xamarin Forms WPF项目中的OxyPlot,如何更改跟踪器文本颜色
- javascript - 重写reduce方法js的问题
- angular - Nativescript + Angular ScrollView 滚动到最终监听器
- java - 如何在JAVA中动态转义JSON中的双引号
- java - Spring Data Rest:发布与非导出实体相关的实体
- python - 如何按其键内的值对字典进行排序?
- visual-studio - 如何在 Azure DevOps 上克隆项目?