✅ Having trouble handling errors when registering a new user
So my application is a .NET web api with a React front end, and im trying to handle all my errors on the backend during the register process and I dont seem to understand how errors are handled. When a user signs up im trying to account for all possible issues they could run into. For example wrong password length, missing special characters, uppercase, etc and then the same for email for example is it a valid email, is there any mistakes in the email for instance
test@test,com
as opposed to [email protected]
I noticed that modelstate is always valid with email part, but for password things seem to work.
the error that gets thrown when the email is not in a correct format actually comes from here var result = await _userManager.CreateAsync(user, registerRequestDTO.Password);
and it throws this error "Username 'test1@test,com' is invalid, can only contain letters or digits."
and I can't seem to figure out how to make it handle this error correctly so that it is in the format below, I don't think I can just hard code it because what if a different error is thrown, i want it to always come back in the format, Key: ['array of errors', '...' ]
like below.
But I'm not sure how to achieve that. This is what I set up for my code currently and that specific error always hits the ApplicationException
I'll attach the code in a gist since there is so much of it https://gist.github.com/CydoEntis/2d9160d6867651f8209214334779a3fe5 Replies
I think I might have come up with a viable solution where I create a my own exception and then deliberately check for the error message and throw that error
I am all ears if there is a better solution then this though
i wouldn't use a string message in the exception
i would either use a slug and let the ui translate it in the right string or return an enum (for the error type) and again have a translation for that in the ui
So instead pass something like ErrorCodes.InvalidEmailFormat, and then on the front end have a look up table that will look for that error code and have the custom error message like "Email must in the correct format"
for a bigger and more formal project i would certainly go that way; i don't know the size of this project in particular so it still depends
Alright ill do that thanks.