C
C#3mo 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))}");
}
}
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))}");
}
}
6 Replies
Angius
Angius3mo ago
Just make sure the exceptions make sense (so no generic Exception) and handled them in the exception-handling middleware Basically, throw a custom NotFoundException or a ConflictException Then, in the exception-handling middleware do something like
return exception switch {
NotFoundException => new NotFoundResult(),
ConflictException => new ConflictResult(),
// ...
_ => new ServerErrorResult()
};
return exception switch {
NotFoundException => new NotFoundResult(),
ConflictException => new ConflictResult(),
// ...
_ => new ServerErrorResult()
};
Otherwise, any exception you throw will result in 500 Internal Server Error
Alex
Alex3mo ago
okay, thank you
Angius
Angius3mo ago
Alternatively, use some sort of a result pattern
Alex
Alex3mo ago
I'll check it and decide which one is more suitable
sibber
sibber3mo ago
$close if you have no further questions :)
MODiX
MODiX3mo ago
Use the /close command to mark a forum thread as answered