✅ 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);
}

}
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();

}
[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();

}
5 Replies
333fred
333fred11h ago
You didn't await RegisterUser You're just firing the task off, then immediately returning a success status. You need to await your tasks to make sure they're completed
Shadow Wizard Money Gang
Thank you. I'm definitely lacking attention to detail. It happens over and over but it's hard to tell for myself.
333fred
333fred11h ago
If that's it, please be sure to $close the thread
MODiX
MODiX11h ago
If you have no further questions, please use /close to mark the forum thread as answered
Anton
Anton9h ago
don't ignore compiler warnings

Did you find this page helpful?