© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
9 replies
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
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))}");
    }
}
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))}");
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Understanding how to build controllers.
C#CC# / help
4mo ago
What is the best way to return errors in api controllers?
C#CC# / help
2y ago
✅ How to handle commands in TreeView?
C#CC# / help
3y ago
❔ How to handle null in Interface
C#CC# / help
3y ago