Working with Exceptions - YoussefSell/Result.Net GitHub Wiki

The library exposes several functions to help you work with exceptions in a simple manner.

1. Converting Exceptions to Result Objects:

To convert an exception to a Result Object, you can use the ToResult() function.

public Result DoSomeWork()
{
  try
  {
    // your code goes here
    return Result.Success();
  }
  catch(Exception ex)
  {
    return ex.ToResult();
  }
}

You can check the code of the function to see what it does to convert the exception to a result object: ToResult().

If you want to add the exception as an error to an existing result object, you can use WithError():

public Result DoSomeWork()
{
  try
  {
    // your code goes here
    return Result.Success();
  }
  catch(Exception ex)
  {
    return Result.Failure()
      .WithError(ex);
  }
}

2. Converting Result Objects to an Exception:

To convert a result object to an exception, you use this function: ToException(). The return type of this function is a custom exception type which is ResultException. This type inherits from Exception and adds a few properties on top of it.

public class ResultException: Exception {
    /// <summary>
    /// The error code associated with this result exception
    /// </summary>
    public string Code { get; set; }
    /// <summary>
    /// The list of errors associated with the result exception.
    /// </summary>
    public ICollection<ResultError> Errors { get; }
    /// <summary>
    /// A unique log trace code used to trace the result in logs
    /// </summary>
    public string LogTraceCode { get; }
}

The full class code can be found here.

var result = SomeOperation();
// if the operation has failed we will convert the result to exception
if (result.IsFailure()) {
    ResultException ex = result.ToException();
    
    /**
    to convert and throw 
    result.ToException().Throw();
    */
}

Now, let's say that you want to convert the result object to a custom exception type based on the result object's failure. Utilizing the Code property, we can do that very easily. We just need to register a mapping between the Code and our exception using ResultExceptionMapper. Here is an example:

// let's assume that we need to throw an exception of type InvalidEmailHostException 
// when the operation failed because the email has an invalid host.
// define the exception -> code mapping
Result.Configure(config =>
{
    config.ExceptionMapper.AddMapping("invalid_email_host", result =>
    {
        // you can use this action to initialize an instance of your exception
        return new InvalidEmailHostException(result);
    });
});
// get the result of the operation
var result = someOperation(email);
// check if the result has failed because the email has an invalid host
if (result.FailedBecause("invalid_email_host")) {
    InvalidEmailHostException exception = (InvalidEmailHostException)result.ToException();
    // your code ...
    /**
    to cast the exception using As<T>():
    var exception = result.ToException()
         .As<InvalidEmailHostException>();
    to convert and throw 
    result.ToException().Throw();
    */
}

As we have seen, the function ToException() returns the type ResultException, so your custom exception must inherit from this type:

public class InvalidEmailHostException : ResultException {
    // your code ...
}
⚠️ **GitHub.com Fallback** ⚠️