[英]Does a middleware have access to middleware error handler?
I am currently using Express and trying to handle a JsonWebToken error gracefully.我目前正在使用 Express 并尝试优雅地处理 JsonWebToken 错误。
I have two middleware functions I have created, one that extracts a user from a jwt token, and one that handles any route errors for specific usecases.我创建了两个中间件函数,一个从 jwt 令牌中提取用户,另一个用于处理特定用例的任何路由错误。
const userExtractor = async (req, res, next) => {
const token = req.token
if (token) {
const decodedToken = jwt.verify(token, process.env.SECRET)
const user = await User.findById(decodedToken.id)
req.user = user
}
next()
}
If token is included and verified, and finds a user from my database with the id inside the token, a user object is attached to any incoming requests.如果包含并验证了令牌,并从我的数据库中找到了具有令牌内 id 的用户,则用户 object 将附加到任何传入请求。
I am trying to error handle when someone sends a faulty token.当有人发送错误的令牌时,我试图错误处理。 The error occurs with jsonwebtoken .verify
method. jsonwebtoken .verify
方法发生错误。
Desktop\backend\node_modules\jsonwebtoken\verify.js:75
return done(new JsonWebTokenError('invalid token'))
My error handle should be handling this specific error, however I am not sure if how middlewares work this is possible.我的错误句柄应该处理这个特定的错误,但是我不确定中间件是如何工作的。
const errorHandler = (error, req, res, next) => {
if (error.name === "JsonWebTokenError") {
return res.status(400).json({error: 'invalid token has been sent'})
}
next(error)
}
And yes, I have initiated both middlewares, with the error handler specifically being the last middleware used at the end.是的,我已经启动了这两个中间件,错误处理程序特别是最后使用的最后一个中间件。
// Util middleware
app.use(middleware.tokenExtractor)
app.use(middleware.userExtractor)
// Routes
app.use('/auth', authRouter);
app.use('/api/me', meRouter)
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.use(middleware.errorHandler)
To handle an error in a middleware need to try catch
section so with return the next(error)
, middleware error will get the error
that happened in the middleware要处理中间件中的错误需要try catch
部分,因此使用 return next(error)
,中间件错误将获取中间件中发生的error
try like the below code试试下面的代码
const userExtractor = async (req, res, next) => {
try {
const token = req.token
if (token) {
const decodedToken = jwt.verify(token, process.env.SECRET)
const user = await User.findById(decodedToken.id)
req.user = user
}
next()
} catch (error) {
return next(error);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.