2
votes

i have build a global exception handling for my wcf application. I have a class that implements 'IErrorHandler' and handles the exception. I can register the ErrorHandler with a 'IServiceBehavior' attribute. (So i don't need to touch every function)

I use the class 'FaultException' to wrap my exception object.

Dim sysEx As SystemException = 'Do Convert
Dim fex As New FaultException(Of SystemException)(sysEx, sysEx.Message)
Dim faultMessage As MessageFault = fex.CreateMessageFault
fault = System.ServiceModel.Channels.Message.CreateMessage(version, faultMessage, fex.Action)

Now I can retrieve the error message at client side. But unfortunally I can't retrieve the original exception type or the original stacktrace.

Is there an easy option to solve the problem without adding 'FaultContract' to each function in my service?

Thank you

3

3 Answers

1
votes

Steve & Saravanan are both correct. Here is how to create a custom fault type & how to use it:

Custom fault contract:

[DataContract]
public class UncaughtErrorFault
{
    [DataMember]
    public string ExecptionType { get; set; }

    [DataMember]
    public string Message { get; set; }

    [DataMember]
    public string StackTrace { get; set; }
}

IErrorHandler method override:

public void ProvideFault(Exception error,
                         MessageVersion version,
                         ref Message fault)
{
    var fe = new FaultException<UncaughtErrorFault>(
        new UncaughtErrorFault
            {
                ExecptionType = error.GetType().Name,
                Message = error.Message,
                StackTrace = error.StackTrace
            },
        error.Message,
        FaultCode.CreateReceiverFaultCode(
            new FaultCode(error.GetType().Name)));

    var mf = fe.CreateMessageFault();

    fault = Message.CreateMessage(version, mf, fe.Action);
}
1
votes

Using FaultContracts and throwing FaultExceptions with custom Fault types is the recommended way of handing exceptions in WCF. If you need to retrieve the stack trace on the client side, you can set includeExceptionDetailInFaults to true in your WCF behaviour config.

0
votes

In IErrorHandler.ProvideFault you are getting the exception in the first parameter. You can wrap that in your custom FaultMessage.

IErrorHandler.ProvideFault(Exception error, MessageVersion ver, ref Message fault)

Please refer to IErrorHandler Interface. This page provides an example on how to do this exception wrapping.