Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monotouch: WCF services and Exception handling

I'm using a WCF service created with Visual Studio.

I'm doing a call such as GetDataAsync(param) for retrieve data. In the GetDataCompleted handler, I'm using the retrieved data.

The service works. Sometimes I can't retrieve data. In this case, an exception occurred like the following:

Exception in async operation: System.Net.ProtocolViolationException: The number of bytes to be written is greater than the specified ContentLength.
  at System.Net.WebConnectionStream.CheckWriteOverflow (Int64 contentLength, Int64 totalWritten, Int64 size) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:546 

How is it possible to catch a similar excpetion? The application still working but the exception is printed at console. I think the exception cames from Channel or something else.

Thank you in advance.

like image 853
Lorenzo B Avatar asked Mar 30 '11 13:03

Lorenzo B


2 Answers

Unfortunately these WCF exceptions can't be caught in Monotouch at present. This seems to be a known bug. See MonoTouch - WCF Services made by Silverlight tool - Can't catch exceptions

like image 171
Dale Avatar answered Oct 07 '22 00:10

Dale


Your question is:

How is it possible to catch a similar (red: ProtocolViolationException) exception?

In your service application, catch the ProtocolViolationException with the following code:

catch (ProtocolViolationException ex)
{
  // do something with your exception here
  // for example, throw a FaultException that will be communicated to the client
  throw new FaultException<ProtocolViolationException> 
        (ex, new FaultReason(ex.Message), new FaultCode("Sender")); 
}

For this to be send back to the client correctly, you'll need to set up an additional attribute on the operation contract, like:

[OperationContract()] 
[FaultContract(typeof(ProtocolViolationException))] 

And then, on the client side you can anticipate this specific exception and handle it gracefully, like:

catch (FaultException<ProtocolViolationException> ex) 
{ 
    Console.WriteLine("FaultException<>: " + ex.Detail.GetType().Name + " - " + ex.Detail.Message); 
} 

Does that answer your question?

like image 31
kroonwijk Avatar answered Oct 07 '22 00:10

kroonwijk