I am currently using Express and trying to handle a JsonWebToken error gracefully.
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.
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.
I am trying to error handle when someone sends a faulty token. The error occurs with jsonwebtoken .verify
method.
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)
CodePudding user response:
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 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);
}
}