C#C
C#2y ago
Alex

✅ How to handle errors in services/controllers

Hi! I do most of work in services and then call the method in the controller. What's the proper way to handle errors that occur in service? I need return error to the frontend (the error model must be consistent). Is it fine to throw error in the services or is there a better way?
Here is example of AccountService method
public async Task RegisterAsync(RegisterDto dto)
{
    IdentityUser? foundUser = await _userManager.FindByEmailAsync(dto.Email);

    if (foundUser != null)
    {
        throw new Exception($"Email '{dto.Email}' is already registered");
    }

    IdentityUser userToCreate = new IdentityUser
    {
        UserName = dto.Email,
        Email = dto.Email
    };

    IdentityResult result = await _userManager.CreateAsync(userToCreate, dto.Password);

    if (!result.Succeeded)
    {
        throw new Exception($"Failed to create user:{string.Join(',', result.Errors.Select(e => e.Description))}");
    }
}
Was this page helpful?