Programming - Silverlight and WCF Fault contracts
As most
Silverlight
.NET developers who use WCF know,
Silverlight doesn't support FaultContracts, and a 404
exception will be returned if the Services do throw an
exception.
The way to fix this is create an encapsulating Interpreter
class which is the default return value for all calls. You can
then enapsulate resultant data in here and explicitly deal with
an exception on the WCF side, by interpreting it and providing
the exception in the resultant adapter.
A quick example is provided below:
[DataContract]
and public class Response
and {
and
[DataMember]
and public bool
BooleanResult { get; set; }
and
[DataMember]
and public Exception
Error { get; set; }
}
and [DataContract]
and public class Exception
and {
and [DataMember(Order =
0)]
and public string
Message { get; set; }
and [DataMember(Order =
1)]
and public
CustomException InnerException;
and public Exception
ToException()
and {
and
Exception e;
and
CustomException ce = this;
and
if (ce.InnerException != null)
and
{
and
Exception inner = ce.InnerException.ToException();
and
e = new Exception(ce.Message, inner);
and
}
and
else
and
e = new Exception(ce.Message);
and
return e;
and }
and }
So, an example of how to handle an exception in a services
method would be:
[OperationContract]
and public Response
ProcessRequest(RequestData request)
and {
and
return Process(request);
and }
and private Response Process(RequestData
request) {
and Response result =
new Response();and
try
and {
//your
operation
and
}
and catch (Exception
ex)
{
and//So
error has been thrown so enapcsulate it properly and send it
back
and
while (ex.InnerException != null)
and
ex = ex.InnerException;
and
result.Error = new Exception();
and
result.Error.Message = ex.Message + ex.StackTrace;
}
return
result;and
and }