Faraz_Ahmed

Hi Guys,

We are writing WCF services which are utilizing COM+ application, now we are unable to decide on exception management i.e. whether to use error codes or exception for business errors. Let me give you an example:

public Document GetDocument(int docId)

Now there can be following outputs when you call this method

- throws exception if database is down

Can be easily handled via exception management

- Returns null if document not found

- Returns null if document is not in active state (Business case)

Now the above cases, they return the same output but the reasons are different and we want to show the reason to the client, what can be the best practice

One of the options we were thinking of

public Document GetDocument(int docId, out enum returnErrorCode)

so enum can have values DocumentNotFound, DocumentNotInActiveState etc

First of all we don¡¯t like this approach and secondly caller will have to do lot of if checks after the method call which is weird.

The other option we are thinking to have two type of base exceptions derived from WCF FaultException, one to handle all unknown/technical exceptions and one to handle pure business errors with ErrorCode in it. The only benefit we'll be getting with this approach that WCF clients will be handling just these exceptions instead of writing various if checks. But still not sure it¡¯s correct to handle business errors via exceptions.

Please advice.

Regards

Faraz



Re: Architecture General WCF: Error Code vs Exception?

Lowendahl

For good service design I would say you should utilzie SOAP faults (in WCF the abstractions for SOAP faults are Fault Contracts and FalutException)





Re: Architecture General WCF: Error Code vs Exception?

Ollie Riches

First of all if you are developing using a service orientated paradigm why are you passing simple types to an end point surely you want to be submitting a 'request' message and receiving a 'response' message back, also naming a method 'GetXXX' seems like a bad idea to me.

e.g.

RetrieveDocumentResponse RetrieveDocument(RetrieveDocumentRequest)

The advantage of this is that the response message 'RetrieveDocumentResponse' can contain a status field indicating success, the document and a error message field etc...

Personally I prefer not to use exceptions to convey errors in business logic across a service boundary, I prefer the above approach. I only expect exceptions from infrastructure\message (versioning)\hosting problems, e.g. the end point of the web service is not available (404 error) etc

Hope this helps

Ollie Riches






Re: Architecture General WCF: Error Code vs Exception?

Faraz_Ahmed

Well agree with you but based on circumstances you cannot follow the full practice some time, can you So it's a kind of SOA but not 100% of course, but anyway the question remains same Error Code or Exception

Regards
Faraz




Re: Architecture General WCF: Error Code vs Exception?

Udi Dahan The Software Simplist

You raise the more generic question of how to handle multiple (and multiple kinds of) responses - one of WSDL's shortcomings.

Consider moving to a generic signature like: IMessage[ ] Execute(IMessage[ ] input);

Then consider moving to a publish/subscribe model.

Finally, you'll find that (as this post shows) you don't need any request/response semantics for getting information .

Give it a try. It's more scalable than the synchronous request/response the tools auto-magically spit out.






Re: Architecture General WCF: Error Code vs Exception?

Paulo Morgado

You could try a more simplistic approach:

GetDocumentResponse GetDocument(GetDocumentRequest request)

GetDocumentRequest would have everything you need to call the service (input parameters, service/application parameters, etc.)

GetDocumentResponse would have the data you want to retrieve and the execution status.

You should leave SOAP as transport only. That way you can easily consume/expose services using other "protocols" (like REST, RSS, etc.).

This suggestion doesn't invalidate anything Udi said about the publisher/subscribe model. It's just a simplier and not so generic service contract.






Re: Architecture General WCF: Error Code vs Exception?

pkr2000

re: exception vs error code
The argument in services is, IMO, exactly the same as it is anywhere else. If you don't expect the problem to ever happen then it is an exception. If you are breaking a business rule then you are probably expecting it to be broken and therefore it isn't an exception.






Re: Architecture General WCF: Error Code vs Exception?

Paulo Morgado

My point is that SOAP is transport and SOAP faults should be only for transport errors.

Some error might not be a business error from the producer's standpoint, it certainly is one form the consumer's standpoint.

You don't expect to receive a FileNotFoundException because the products file is missing when you call GetProducts. Instead you should get some sort of internal error.






Re: Architecture General WCF: Error Code vs Exception?

pkr2000

I'd have to agree with that, you wouldn't expect an infrastructure file to be missing that would be ideal for an exception. However I'm still unclear as to what this thread is suggesting as the answer. The quote from Ron Jacobs is interesting...

According to the .NET FrameworkClass Library Design Guidelines

¡°Exceptions are the standardmechanism for reporting errors. Applications and libraries should not usereturn codes to communicate errors. The use of exceptions adds to a consistentframework design and allows error reporting from members, such as constructors,that cannot have a return type. Exceptions also allow programs to handle theerror or terminate as appropriate. The default behavior is to terminate anapplication if it does not handle a thrown exception.¡±

Consider a seemingly simply business rule, "Can you transfer your x units from account 1 to account 2 ". The rules check for; a) account 1 exists b) have rights to account 1 c) does account 2 exists...etc, n) does account 1 have the funds n+1) is account 2 open

As a service your "contract" is explain exactly the rule that was broken. If we were to recommend the error code result it would require a large switch statement to process all the "error" codes - not nice and difficult to maintain. If we were to recomment an exception per rule we'd end up with a horrible set of catch (n)...catch(n+1) structure, IMO worse still (at least a switch can group codes). I believe what we're suggesting is that you'd have one TransferException with arguments describing the specific results But wouldn't that simply result in one catch(n) and a switch statement on the argument I suppose at least this solves the "you can ignore an error code" and the horrible catch(n)...catch(n+1) problems.

Or have I missed something






Re: Architecture General WCF: Error Code vs Exception?

Paulo Morgado

I think service invocations should be treated as low level invocations and exceptions should be a high level mechanism.

A SOAP fault should be a transport error when using SOAP. When using REST, HTTP status codes and messages should be used.

When using SOAP faults you can get a FaultException or a SoapException depending whether you are using WCF or ASMX. Should you build your service consumers be aware of the API over the transport either

And you can also be accessing a database or a file (on a local drive or via FTP).

You should shield all this from the business invocation code and throw transport or communication exceptions.

As for business rules, a business exception should be thrown.

With this pattern, everyone will be happy:

¡¤ No FaultExceptions or SoapException

¡¤ Exceptions thrown when an error occurs.






Re: Architecture General WCF: Error Code vs Exception?

Ollie Riches

IMO fault\error\exception (which ever you like to call it) is never nice to look at in the 'real' world of application development, whether it be a exception handling strategy like the enterprise library exception handling block, detailed error messages\codes or multiple 'catch' statements.

Just as long as you decide on a strategy you can justify and use it every where then it should be okay.

As I & others have stated above I believe you shouldn't throw exceptions from a service - detailed error codes\messages should be returned in the response message, only the communication infrastructure (e.g. SOAP via HTTP) should throw exceptions.

HTH

Ollie Riches






Re: Architecture General WCF: Error Code vs Exception?

Faraz_Ahmed

Sorry guys for coming so late on it, anyway i think you guys are thinking totally from WCF perspective and whatever comments you all have given are totally correct in WCF world. Ok lets say if i remove SOA all together and you have COM+ services in place of it, what you will do than or if i keep service layer either as WCF or COM+ or webservices but there's a business layer written in custom .net classes what they'll return then
like lets say WCF ProductManagerService calls CreateProduct and internally it calls Create of Product BLL class then how this BLL would handle the errors via exception or error codes

Regards
Faraz




Re: Architecture General WCF: Error Code vs Exception?

Ron Jacobs

My blog post that was quoted earlier is here.
Keep in mind that the goals are still the same whether or not you are involving services The goals are:

  1. Easy to understand, code and use
  2. Consistent with the intent of the language/technologydesigners and common practice
With that said, I believe that exceptions are still the best way to go in either case. Some people have noted that exceptions may introduce a performance problem, however this is only in rare cases where the number of exceptions thrown are really excessive (like hundreds of thousands). If that is your concern, I would test the performance to know for sure.




Re: Architecture General WCF: Error Code vs Exception?

Paulo Morgado

I have never done any real work with COM+ but I've done some mixed REST/ASMX/WCF clients and I thinl I would do the same for COM+ - an abstraction layer for comunication and business errors would be on the message (or data transfer object).

As I said before, that doesn't prevent you from throwing a business exception from the client service calling code to the code calling the code that calls the service.






Re: Architecture General WCF: Error Code vs Exception?

Paulo Morgado

Let me just code what I mean.

This would be the service consuming code:

Code Snippet

// ...

IProductsService productsService = ServiceContainer.GetService();

try

{

Product[] productsService.GetProducts(category);

}

catch (InvalidProductCategoryException bex)

{

// ...

}

catch (ProductSystemException exe)

{

// ...

}

// ...

This would be a service adapter for WCF:

Code Snippet

public class WcfProductsServiceAdapter : IProductsService

{

public Product[] GetProducts(string category)

{

GetProductsRequestMessage request Translators.Get(category);

Adapters.BeforeSendMessage(request);

GetProductsResponseMessage response;

using (ProductsServiceClient client new ProductsServiceClient())

{

try

{

response = client.GetProducts(request);

}

catch(Exception ex)

{

throw new ProductSystemException(ex.Message, ex);

}

}

Adapters.AfterReceiveMessage(response); // throws business exceptions

// based on error information

// on the respone message.

return Translators.GetList<Product>(response);

}

}

Using this pattern, you can have your code receiving business exceptions even if the comminication code is nto using exceptions for business errors.

Using this pattern, you can implement your service adapter using WCF with MessageVersion.None, ASMX, COM+, database, XML file, etc.

I hope I understood correctly the question: WCF, FaultException and business errors, right