0

I use LangExt library and i have the case of no user exists with UserId 1.

public async Task<Option<UserViewModel> GetUser()
=> await GetUser(1)
          .MapAsync(this.alterName)
          .MapAsync(this.alterCountry)
          .MapAsync(this.applyMoreChange)
          .Map(this.mapper.map<ViewModel>);

since no user exists for userId 1, the GetUser(1) returns Option<None> and the remaining code fails with the exception

LangExt.ValueIsNoneException : Value is None.
at languageExt.OptionAsyncAwaiter`1.GetResult()

How to handle this case.? and to make sure the mapAsync and map chaining execute only if option is some user and not none.

EagerToLearn
  • 89
  • 12

1 Answers1

0

This page on github seems to indicate that option will have a .IfSome() function. The github gives the following code snippet:

// Returns the Some case 'as is' and 10 in the None case
int x = optional.IfNone(10);

// As above, but invokes a Func<T> to return a valid value for x
int x = optional.IfNone(() => GetAlternative());

// Invokes an Action<T> if in the Some state;
optional.IfSome(x => Console.WriteLine(x));

A suggestion on implementation (without knowing the full idea of your project) would be something like this:

public async Task<Option<UserViewModel>> GetUser(int num)
{
    var user = await GetUser(1);
    if (user.IsSome)
    {
        user.MapAsync(this.alterName)
            .MapAsync(this.alterCountry)
            .MapAsync(this.applyMoreChange)
            .Map(this.mapper.map<ViewModel>);

        return user;
    }
}
SteveOh
  • 96
  • 7
  • this doesn't satisfy my needs as inner lambda does not have mapAsync methods. – EagerToLearn Mar 15 '22 at 17:27
  • @EagerToLearn Is using lambda required? You could bring the code out into a function where you await GetUser, then check if the result IsSome, and if so continue to execute the mapping commands on the user. Would this work in your use-case? – SteveOh Mar 15 '22 at 17:58
  • could you please share Code sample for the suggestion .? – EagerToLearn Mar 15 '22 at 20:14
  • @EagerToLearn I added an example, though without knowing the full scope and idea of your project I can't really test it myself. – SteveOh Mar 15 '22 at 20:30