Is this good use of try…catch, or should I write everything in try block? I am trying to prevent nested try…catch blocks.
JavaScript
x
16
16
1
router.post('/refresh', async (req, res) => {
2
const refreshToken = req.body.token;
3
let decoded;
4
5
try {
6
decoded = jwt.verify(
7
refreshToken,
8
process.env.REFRESH_TOKEN_SECRET,
9
);
10
} catch(error) {
11
return res.sendStatus(401);
12
}
13
14
// … use decoded variable here
15
});
16
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:
JavaScript
1
19
19
1
router.post('/refresh', async (req, res) => {
2
let decoded;
3
4
try {
5
const refreshToken = req?.body?.token;
6
if ( ! token ) {
7
throw new Error('Token not supplied!')
8
}
9
decoded = jwt.verify(
10
refreshToken,
11
process.env.REFRESH_TOKEN_SECRET,
12
);
13
} catch(error) {
14
return res.sendStatus(401);
15
}
16
17
// … use decoded variable here
18
});
19