Harry
Harry

Reputation: 4835

Declaring immutable variable in try catch block, that is accessible outside the block?

I have a simple try catch block that attempts to authorise a user and sets the usedId to the relevant attribute from the decoded token, as follows:

let userId;
try {
    const decodedIdToken = await validateIdToken(request);
    userId = decodedIdToken.user_id;
} catch (error) {
    response.status(403).send(error);
    return;
}

const question = {
        author: userId,
        text: request.body.text,
        tags: request.body.tags,
    }

While this works, the mutability of the userId variable bothers me as it might be possible to attempt to use it elsewhere and find it's undefined since we haven't given it any value when initially declared. If I don't declare it outside the try block using let, i.e. I declare it inside the block using const and thus making it immutable, it's scoped to the try block and can't be used elsewhere.

One option is to use var inside the try block to hoist it, but again this is mutable and hoisting comes with its own potential pitfalls, so I prefer not to use it.

Is there a generally accepted patter for declaring variables like this, where the call that sets the value might fail (necessitating the try catch block)?

Upvotes: 0

Views: 1293

Answers (1)

jfriend00
jfriend00

Reputation: 707706

You don't show the code that wants to use the variable so it's hard to make a specific recommendation for this particular code, but this is a common issue in Javascript and there is no pretty solution. Depending upon the code specifics, you can sometimes move the other code that wants to use the variable to be inside the try block so its in scope.

If that's not feasible, then you have to do as you already know which is declare the variable before the block with let or declare it within the block with var. I personally would avoid var.

You could also factor the code out into an function (with some of the other code that wants to use the variable) that either resolves with your value or rejects, but that may just leave you with the same issue (depending upon the rest of the code).

P.S. Wouldn't your catch block normally have a return in it so you don't continue execution after the try/catch? If you show us the whole request handler, we can make specific recommendations.

Upvotes: 2

Related Questions