jsonwebtoken, jwt crashing my app when invalid token is provided even though errorHandler middleware catches the error

Viewed 279

Full github repo https://github.com/suubcity/fso-blog-list/tree/bb3b8f623da4d9a5dcf87c2d82ccf3715dfbd3fb

When an invalid token is sent to this line of code...

const decodedToken = jwt.verify(req.token, process.env.SECRET);
            'TYPEOF:',

I want to handle it with the error handler below. The error handler works, I get the status code and json returned however my app still crashes. How can I prevent the crash?

middleware

const errorHandler = (err, request, res, next) => {
    logger.error(err.message);

    if (err.name === 'ValidationError') {
        return res.status(400).json({ error: err.message });
    } else if (err.name === 'JsonWebTokenError') {
        res.status(401).json({ error: 'invalid token' });
    }

    next(err);
};

error message

Connected to MongoDB
Server running on port 3001
invalid signature
POST /api/blogs 401 25 - 9.366 ms
JsonWebTokenError: invalid signature
    at /home/martyn/Documents/projects/fso-blog-list/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/home/martyn/Documents/projects/fso-blog-list/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/home/martyn/Documents/projects/fso-blog-list/node_modules/jsonwebtoken/verify.js:94:10)
    at /home/martyn/Documents/projects/fso-blog-list/controllers/blogs.js:13:27
    at newFn (/home/martyn/Documents/projects/fso-blog-list/node_modules/express-async-errors/index.js:16:20)
    at Layer.handle [as handle_request] (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/route.js:112:3)
    at newFn (/home/martyn/Documents/projects/fso-blog-list/node_modules/express-async-errors/index.js:16:20)
    at Layer.handle [as handle_request] (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/layer.js:95:5)
    at /home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/index.js:335:12)
    at next (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/index.js:174:3)
    at router (/home/martyn/Documents/projects/fso-blog-list/node_modules/express/lib/router/index.js:47:12)
    at newFn (/home/martyn/Documents/projects/fso-blog-list/node_modules/express-async-errors/index.js:16:20)
0 Answers
Related