I am attempting to register a user using a register function from an ASP.NET Web API POST request. When an email address that has already been used to register a user is used again, the server throws an error. And when a new email is used, the user is added to the DB successfully. I want to be able to display an error notification (Material Snack bar) when the error is displayed, and then reset the registration form and display a success notification if no error is displayed and a user is added.
The register function found within the Web API is as follows:
[HttpPost]
[Route("Register")]
public ActionResult Register(AuthVM vm)
{
using var db = new NorthwindContext();
// Check if User exists
if (this.UserExists(vm.EmailAddress))
{
return Forbid();
}
// Create new user
var newUser = new UserLogin
{
EmailAddress = vm.EmailAddress,
Password = this.ComputeSha256Hash(vm.Password),
Name = vm.Name
};
// Add new user to db
try
{
db.UserLogin.Add(newUser);
db.SaveChanges();
return Ok();
}
// else throw exception error
catch (Exception e)
{
return BadRequest(e.Message);
}
}
The UserExists function (checks whether the email entered exists on the DB or not)
public bool UserExists(string EmailAddress)
{
using var db = new NorthwindContext();
var user = db.UserLogin.Where(zz => zz.EmailAddress == EmailAddress).FirstOrDefault();
return user != null;
}
Then lastly, the subscribe to register (called when the registration form is submitted), within the Angular application.
onSubmit() {
if (this.service.registerForm.valid) {
this.service.register().subscribe(
(res: any) => {
if(res) {
this.openErrSnackBar();
} else {
this.service.registerForm.reset();
this.openSnackBar();
this.router.navigate(['/login']);
}
}
);
}
}
The above works for the most part, when a email address that has not yet been used is entered, the else section is executed and the user is successfully registered, and the success notification is displayed and the page is re-routed to the login screen.
However, when an email address that already exists is entered, the if part supposedly executes, assuming 'res' is found to be true. Inside my console, i receive the following error when a user is registered using an already existing email:
The above error is displayed, yet the function 'openErrSnackBar()' does not run? Any help or guidance is appreciated.

ForbidtoBadRequest. BTW, its not thread-safe to split check for user and its insertion. If you have unique constraint on e-mail in database then there's no need inUserCheckat all - you'll have an exception inSaveChanges()and sendBadRequestback to angular