Home > Enterprise >  How to get the result of an asynchronous operation in case of an exception?
How to get the result of an asynchronous operation in case of an exception?

Time:11-26

There is such a code in which the first method can throw an exception (for example, if the connection to the database fails). But, in this case, we absolutely need to get and return the result of the second (Method 2) asynchronous method. If everything is fine with the first method and there is no exception, then we return the data from the first method. I hope I explained it clearly :) So, how to do it wisely?)

public async Task<IEnumerable<User>> GetUsersAsync(int departmentId,
    CancellationToken token)
{
    try
    {
        // Method 1: An exception can be thrown here
        var usersFromSqlDb = await _userSqlRepository
            .GetUsersAsync(departmentId, token); 

        if (!usersFromSqlDb.Any())
        {
            // Method 2
            var usersFromMongoDb = await _userMongoRepository
                .GetUsersAsync(departmentId, token);
            return usersFromMongoDb;
        }

        return usersFromSqlDb;
    }
    catch (CannotAnyUserException)
    {
        throw;
    }
    catch (Exception ex)
    {
        throw new CannotAnyUserException();
    }
}

CodePudding user response:

An idea is to have two return points. One for the case that the Method 1 succeeds and has a non-empty result, and a second one for all other cases:

public async Task<IEnumerable<User>> GetUsersAsync(int departmentId,
    CancellationToken token)
{
    try
    {
        // Method 1: An exception can be thrown here
        var usersFromSqlDb = await _userSqlRepository
            .GetUsersAsync(departmentId, token); 
        if (usersFromSqlDb.Any()) return usersFromSqlDb;
    }
    catch { } // Suppress the exception

    // Method 2
    var usersFromMongoDb = await _userMongoRepository
        .GetUsersAsync(departmentId, token);
    return usersFromMongoDb;
}
  • Related