error-or
error-or copied to clipboard
How do you catch error out side the domain
Hi, many thanks for this tool,
Please see the code the below from your examples:
ErrorOr<Deleted> DeleteUser(Guid id) { var user = await _userRepository.GetByIdAsync(id); if (user is null) { return Error.NotFound(code: "User.NotFound", description: "User not found."); }
await _userRepository.DeleteAsync(user);
return Result.Deleted;
}
How do you capture an error from this line: await _userRepository.DeleteAsync(user); Using your tool so that you can include it in the returned results to the front end to inform the user that the record can not be deleted?
Many thanks Zak
@zaktecs https://www.youtube.com/watch?v=tZ8gGqiq_IU&list=PLzYkqgWkHPKBcDIP5gzLfASkQyTdy0t4k&index=5
I do not no if its the best way, but in my I either catch the exceptions inside the repository (they are usually unexpected), for example in my repository so:
public async Task<ErrorOr<Deleted>> DeleteUserByNameAsync(string username)
{
try
{
var user = await this._userManager.FindByNameAsync(username);
if (user == null)
{
return Errors.User.DoesNotExist;
}
var result = await this._userManager.DeleteAsync(user);
return result.Succeeded ? Result.Deleted : Errors.Database.DeleteFailed;
}
catch(Exception ex)
{
return Error.Unexpected("Database.DeleteUser.Unexpected", ex.Message);
}
}
or use an additional exception handling middleware for all these unexpected failures and transform the exceptions there:
app.UseExceptionHandler(appError => appError.Run(async context =>
{
// add exception handling here...
}));
@zaktecs, global error handling (exception handler middleware, for example, as @kgnet88 suggested) should probably be implemented regardless of using ErrorOr
or exceptions.
Regarding your question, if it's your code, you can have your delete async return an ErrorOr
, for example:
ErrorOr<Deleted> DeleteAsync(..)
If it's not your code, you can either wrap it with a try-catch and return an Error
object, or, if appropriate, handle it in your global exception handling logic.