Express Mongoose在回调中抛出自定义错误



我正试图从mongoose回调中抛出一些自定义错误类。这是一个简单的代码

const Restaurant = require('../models/Restaurant')
const { InternalServerError, UnauthorizedError } = require('../errors/errors')
const checkRestaurantAuthorization = async (token) => {
const restaurant = Restaurant.findOne({ 'token': token }, function (error, result) {
if (error) throw new InternalServerError()
else if (!result) throw new UnauthorizedError()
else return token
})
}

在我的代码中,checkRestaurantAuthorization是由这样的简单中间件调用的

const restaurantMidlleware = async (req, res, next) => {
console.log('Request Type:', req.method);
try {
token = await checkRestaurantAuthorization('invalid_token')
next()
} catch (error) {
next(error)
}
}

现在,如果找不到具有给定令牌的餐厅实例,则应用程序将以throw er; // Unhandled 'error' event崩溃。根据我的测试,当调用throw new UnauthorizedError()时,执行似乎停止了,并且我无法确定问题。

如果有用,这里还有一个自定义错误的例子

class UnauthorizedError extends Error {
constructor(message) {
super(message)
this.name = 'Unauthorized request'
this.code = 403
Error.captureStackTrace(this, UnauthorizedError)
}
}

我错过了什么?

您是否尝试过将第一个块放入"try-catch"块?

throw语句抛出一个用户定义的异常。当前函数的执行将停止(throw之后的语句将不会执行(,控制权将传递给调用堆栈中的第一个catch块。如果调用方函数之间不存在catch块,则程序将终止。

您可以将代码更改为promise或异步等待

问题的另一个来源可能是,您在一个函数中使用async和回调,试图省略async,然后再次使用它

在中写"const restaurant="没有意义

const restaurant = Restaurant.findOne

因为每个找到的餐厅都将保存在回调的结果变量中

试试这个

function checkRestaurantAuthorization(token){
return new Promise(async(resolve, reject)=>{
try {
const restaurant = await Restaurant.findOne({ 'token': token });
if (!restaurant)
return reject(new UnauthorizedError())
else
return resolve(token)
}catch(error){
return reject(new InternalServerError())
}
})}

更好的方法是只使用async functiontry-catch,而不是返回promise或任何回调

最新更新