private void TransformingErrorWithMapError() { ITry <int, NetworkOperationError> number = Api.GetNumber(); // You can use MapError to map for example from exception to another type you use to represent errors. Or map to logging messages. ITry <int, string> flooredMultiplicationResult = number.MapError(e => e.ToString()); }
private void RetrievingValues() { // A try is a specific case of coproduct. Match methods are applicable for all coproduct types. ITry <int, NetworkOperationError> number = Api.GetNumber(); // Match is the preferred way how to retrieve values of tries (and coproducts in general). It is typesafe and future proof. // This overload takes two functions. Each of those have to return a value and result is stored in the stringifiedNumber variable. string stringifiedNumber = number.Match( result => result.ToString(), _ => "Unfortunately, we failed to obtain a number from the server." ); // This overload accepts two optional functions. If either of them isn't provided, nothing happens for that case. number.Match( n => Console.Write($"Operation successful, result is: {n}."), _ => Console.Write("Operation failed, try again.") ); number.Match(n => Console.Write($"Operation successful, result is: {n}.")); number.Match(ifSecond: _ => Console.Write("Operation failed, try again.")); // Get method will throw an exception for unsuccessful tries that have exception as the error. Using it is an anti-pattern. // You should rather use Match to branch your code into individual cases where each case is guaranteed to work. // This might be needed on the boundary with some other framework where you have to work with exceptions. ITry <int, Exception> numberWithException = number.MapError(e => new InvalidOperationException()); int numberValue1 = numberWithException.Get(); // You can also configure the exception that is thrown by mapping the error inside Get directly. int numberValue2 = number.Get(e => new InvalidOperationException()); int numberValue3 = numberWithException.Get(ex => new Exception("Error when retrieving number", innerException: ex)); // Because try is a coproduct, you can check the value directly. On try, there are named properties for this. IOption <int> successResult1 = number.Success; IOption <int> successResult2 = number.First; IOption <NetworkOperationError> errorResult = number.Error; IOption <NetworkOperationError> errorResult2 = number.Second; }
public void MapError() { Assert.Equal(42, Success.MapError(e => new InvalidOperationException("foo", e)).Get()); Assert.Throws <InvalidOperationException>(() => Error.MapError(e => new InvalidOperationException("foo", e)).Get()); }