✅ Why doesn't this try catch, catch exception.

I have these two methods, in register I have a try catch but it's not catching the exception thrown in the try block. I'm doing something wrong but I cannot figure it out. isEmailUsed is definitely true.

public async Task RegisterUser(UserRegistrationDTO userToRegister)
{
    // await _userRepository.CreateUserAsync(userToRegister);


    bool isEmailUsed = await _userRepository.IsEmailUsedPreviously(userToRegister.Email!);
    if (isEmailUsed)
    {
        throw new Exception("Email is already in use");
    } else
    {
        //create user
        await _userRepository.CreateUserAsync(userToRegister);
    }

}


 [HttpPost("register")]
 public ActionResult<UserRegistrationDTO> Register(UserRegistrationDTO request)
 {
     var validationResult = _userRegisterValidator.Validate(request);

     if (!validationResult.IsValid)
     {
         var problemDetails = new HttpValidationProblemDetails(validationResult.ToDictionary())
         {
             Status = StatusCodes.Status422UnprocessableEntity,
             Title = "Validation failed",
             Detail = "One or more validation errors occured",
             Instance = "api/register"
         };

         return UnprocessableEntity(problemDetails);
     }

     try
     {
         _authService.RegisterUser(request);
     }
     catch (Exception ex)
     {
         return Conflict(ex.Message);
     }

     
     return Created();
   
 }
Was this page helpful?