Skip to content
Advertisement

Should I write all my route handling code in a try-catch block?

Is this good use of try…catch, or should I write everything in try block? I am trying to prevent nested try…catch blocks.

    router.post('/refresh', async (req, res) => {
        const refreshToken = req.body.token;
        let decoded;

        try {
            decoded = jwt.verify(
                refreshToken,
                process.env.REFRESH_TOKEN_SECRET,
            );
        } catch(error) {
            return res.sendStatus(401);
        }

        // … use decoded variable here
    });

Advertisement

Answer

You’ll never need to nest try/catches – a catch() will catch all errors underneath it.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try…catch

Specifically:

The try…catch statement marks a block of statements to try and specifies a response should an exception be thrown.

However if you’re unsure that refreshToken will exist (it’s a good example not to trust web browsers), you can add it to the block you’re catching errors in:

    router.post('/refresh', async (req, res) => {
        let decoded;

        try {
            const refreshToken = req?.body?.token;
            if ( ! token ) {
                 throw new Error('Token not supplied!')
            }
            decoded = jwt.verify(
                refreshToken,
                process.env.REFRESH_TOKEN_SECRET,
            );
        } catch(error) {
            return res.sendStatus(401);
        }

        // … use decoded variable here
    });
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement