Peter D
Peter D

Reputation: 4931

Exception handling pattern for this type of situation?

I have 2 APIs from 2 different companies that allow me to communicate with their servers in order to process transactions. I am tasked with creating a generic interface to these APIs. I came up with something like this:

IServiceProvider <- ServiceProvider <- CompanyAServiceProvider
IServiceProvider <- ServiceProvider <- CompanyBServiceProvider

In CompanyAServiceProvider I am using the API that they offer to interface with their remote servers. This API from company A throws exceptions that are completely different from Company B's.

I can handle the exception locally but I don't really think that suites the situation.

public String purchase(String amount) {
  try {
    request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
  } catch ( InitializationException e ) {
    //do something.
  }
}

Or I can throw this exception to the caller:

public String purchase(String amount) throws Exception {
  request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
}

And let the caller handle just the Exception no matter what that exception is and no matter what API throws it.

How can I write an interface to 2 different APIs and keep it generic when I am dealing with 2 different sets of thrown exceptions. Am I dealing with this correctly? What would be the best choice?

Upvotes: 2

Views: 293

Answers (3)

akf
akf

Reputation: 39485

Another reason to handle the Exception locally and roll your own to throw downstream (when necessary):

There might be work (clean-up, retry, etc) that needs to be performed when a specific type of Exception is thrown that varies from vendor to vendor.

Upvotes: 1

Sheldon White
Sheldon White

Reputation:

Think about what level of abstraction you are dealling with at the level of the calling functions. Presumably you don't want to expose details of the individual companies you are dealing with, and would prefer to deal with more generic concepts like Orders, PurchaceTransactions etc. So the previous poster's advice is good: create a class like PurchaseException, which is a wrapper around the information you got back from the vendor's individual exception classes.

Upvotes: 3

akarnokd
akarnokd

Reputation: 69997

In this case I create my own Exception sublcass and just wrap the actual exception. My API then exposes only my exception.

Upvotes: 14

Related Questions