I am writing a N-Tier application using ASP.Net Core. In my service layer in logic tier I have an API which update the user's password. Here is the code from the service layer.
public IActionResult UpdatePassword([Required][EmailAddress] string email, [Required][DataType(DataType.Password)] string oldPassword, [Required][DataType(DataType.Password)] string newPassword)
{
try
{
_userLogic.UpdatePasswordLogic(oldPassword, email, newPassword);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok($"Password updated successfully. The new password is: { newPassword }");
}
basically it just gets the email, the current password, and the new given password by user and pass it to the "UpdatePasswordLogic" method in business layer. The "UpdatePasswordLogic" works as following:
public void UpdatePasswordLogic(string oldPassword, string email, string newPassword)
{
// Take the user's password from the database
string savedPassword = _context.Users
.Where(x => x.Email == email)
.Select(x => x.Password);
if (!string.IsNullOrEmpty(savedPassword))
{
// Check if the oldPassword is equal to the password saved in the databank
if (ComparePasswords(savedPassword, oldPassword))
{
// TODO: Set the new password
}
else
// Throw exception when password is not correct
throw new Exception("password does not match the one saved in the database");
}
else
// If user does not exist, throw an exception
throw new Exception("User does not exist in databank");
}
The "ComparePasswords" method check if the given password by user match the one that saved in the databank. If the password is not correct then it suppose to throw an exception. When I enter a wrong password the UpdatePasswordLogic does throw an exception but my API in service layer does not catch this exception and it returns the OKObjectResult. Does anyone know why it does not catch the exception?