In my typescript project I am trying to fetch a user from database. Since it is possible that the specific user will not be found, I want to wrap the call inside a try-catch block:
try {
const currentUser = await User.findOrFail(ctx.params.id)
} catch (e) {
return ctx.response.status(409).json({ error: 'User not found' })
}
However, since I need the user outside the try-catch block, this code will raise an error (currentUser is not defined
):
try {
const currentUser = await User.findOrFail(ctx.params.id)
} catch (e) {
return ctx.response.status(409).json({ error: 'User not found' })
}
:
:
return { user: currentUser }
I want to keep the try-catch block wrapping only the fetch call (since later i might have other exceptions). Using var
instead of const
(or let
) will do the work, but I got the impression that using var
is not recommended.
Ideas?