Skip to content

Add Catch<TException> to IPromise and IPromise<TPromised> interface? #57

@sindrijo

Description

@sindrijo

The only difference from a normal Catch is that if the exception does not match the expected type the onRejected handler is not called.

Code that looks like this:

Blackbox.ReturnsPromise()
  .Catch(ex => 
  {
      var specificException = ex as SpecificExceptionType;
      if(ex != null)
      {
          // Handle specific error
      }

      var otherSpecificException = ex as OtherSpecificExceptionType;
      if(otherSpecificException != null)
      {
          // Handle other specific error
      }

      // We didn't handle any of the specific exception types
  }).Then( data => 
  {
      // Do something useful
  });

Then can be written like this:

Blackbox.ReturnsPromise()
  .Catch<SpecificExceptionType>(ex => 
  {
      // Handle specific error
  })
  .Catch<OtherSpecificExceptionType>(ex => 
  {
      // Handle other specific error
  })
  .Catch(ex => 
  {
      // We didn't handle any of the specific exception types
  })
  .Then( data => 
  {
      // Do something useful
  });

The changes required to support this are small. Here is the implementation for the generic promise type.

public IPromise<PromisedT> Catch<TException>(Action<TException> onRejected) 
where TException : Exception
 {
    var resultPromise = new Promise<PromisedT>();
    resultPromise.WithName(Name);
    Action<PromisedT> resolveHandler = v =>
    {
        resultPromise.Resolve(v);
    };

    Action<Exception> rejectHandler = ex =>
    {
        var specificException = ex as TException;
        if (specificException != null)
        {
            onRejected(specificException);
        }

        resultPromise.Reject(ex);
    };

    ActionHandlers(resultPromise, resolveHandler, rejectHandler);

    return resultPromise;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions