I am working on a project using nestjs.
During the project, I was curious about the use of guard.
If I use guard when logging in, I think it is difficult to give feedback on whether the ID is wrong or the password is wrong. I want to give various messages about possible errors.
So I try to do defensive programming through code without using guard. Is it okay to not use guard in this situation? I wonder if it is always good to use guard.
I searched for nestjs that does not use guard, but could not find an answer.
It may be a simple question, but I hope you understand that it is a big concern for me. Thank you.
You don't have to use guards
of course, but these are helper
functions that make our operations much simpler. The first purpose of the guards is to catch the priority error, if there is a situation where you want to catch an error before that, it is not recommended to use the guard there anyway.The example
@Roles(UserRoles.Admin)
@UseGuards(AuthGuard("jwt"),RolesGuard)
async getUser(@Param('userId') userId:string): Promise<Object | User> { // Return Users by name
const user = await this.userService.getUserById(userId)
if(!user) return {msg:"User not found",status:"error"};
return user
}
The first thing
I need to catch before other errors is the user's role and whether she is logged in. We can consider this a priority
.I then used the errors I needed to catch inside
the functions. In general, we prefer to use guards if there are some situations where we need to catch them first.