Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept WCF faults and return custom response instead?

Consider the following very basic WCF service implementation:

public enum TransactionStatus 
{
    Success = 0,
    Error = 1
}

public class TransactionResponse
{
    public TransactionStatus Status { get; set; }
    public string Message { get; set; }
}


[ServiceContract]
[XmlSerializerFormat]
public interface ITestService
{
    [OperationContract]
    TransactionResponse DoSomething(string data);
}   

public class TestService : ITestService
{
    public TransactionResponse DoSomething(string data)
    {
        var result = ProcessData(data); // may throw InvalidOperationException
        return new TransactionResponse() 
        {
            Status = TransactionStatus.Success,
            Message = result                
        };            
    }

    private string ProcessData(string data) 
    {
        if (data = "foobar")
            throw new InvalidOperationException();

        return data;        
    }        
}

In the instance that the DoSomething method does throw an InvalidOperationException, I would like to intercept the fault and return a TransactionResponse object, rather than have WCF raise a FaultException with the client. How can I do this without surrounding each method body in a huge try catch statement? Is there some where I can hook into? Can I do this with some sort of attribute or something? An example of how I would like to handle it can be demonstrated using ASP.NET MVC:

public class ApiController : BaseController
{
    protected override void OnException(ExceptionContext filterContext)
    {
        var ex = filterContext.Exception;
        var message = HttpContext.IsDebuggingEnabled ? ex.ToString() : ex.Message;

        _logger.Error("Error processing request for controller {0}, action {1}",
            filterContext.RequestContext.RouteData.Values["controller"],
            filterContext.RequestContext.RouteData.Values["action"]);

        _logger.Error(ex.ToString());
        filterContext.ExceptionHandled = true;
        filterContext.Result = ToXml(new ApiResult(false)
        {
            Message = message
        });
    }

    // ...
}

Using the above method in MVC, I can ensure that no matter which controller action throws an exception, I can handle it and return an appropriately formatted ActionResult containing the necessary info. Is there a way to do this kind of thing with WCF?

like image 287
Chris Avatar asked Jun 10 '11 16:06

Chris


People also ask

How do you handle a fault exception in C#?

In a service, use the FaultException class to create an untyped fault to return to the client for debugging purposes. In a client, catch FaultException objects to handle unknown or generic faults, such as those returned by a service with the IncludeExceptionDetailInFaults property set to true .

What is exception handling in WCF?

Leverage fault exceptions in WCF to transmit user friendly error messages to the presentation layer when exceptions occur. Exceptions are errors that occur at runtime; exception handling is the technique of handling these runtime errors.

Which exception type is thrown by all WCF component methods?

By default all exceptions thrown from within a service operation will be returned to the client as a FaultException object.


1 Answers

Check out the WCF IErrorHandler interface - it allows you to centrally define one way in your service implementation to catch all exceptions and either swallow them, or convert them to WCF-friendly SOAP exceptions. This will make sure the channel between the client and the server isn't faulted, e.g. it can still be used after this call failed.

I don't understand why you'd want to "catch" the SOAP faults and convert those to something else, though.... nor do I know of any support that WCF would give you. The basic assumption is: catch .NET exceptions and convert them into interoperable SOAP faults

like image 110
marc_s Avatar answered Oct 26 '22 07:10

marc_s