Sam
Sam

Reputation: 2201

WCF Rest .NET 4.0 Unhandled Exceptions

I've found a bunch of questions that were very close to what I need. But I'm worried that I have missed some important information.

How do I catch all unhandled exceptions using WCF Rest with .NET 4.0?

For security purposes I do not want unhandled exceptions going to the client. I want to log all exceptions and for unknown exceptions just send back 500 Internal Server Error.

My best research so far tells me I need to implement IErrorHandler and throw WebFaultExceptions for known exceptions. One issue I have with this is that all of my business logic is in a separate project from the WCF service and it doesn't make sense to throw a Web exception from the underlying class library since the class library could be consumed by another process which may not be a WCF Rest Service. Is there a nice way to map exceptions?

Upvotes: 1

Views: 1538

Answers (1)

VirusX
VirusX

Reputation: 973

Yes, you can implement IErrorHandler and use it to map exceptions. You don't need to throw WebFaultException from your business logic, just throw your custom exceptions.

For example, you can map YourCustomException to some simple json string. Instead of string you can put some object. Sample IErrorHandler.ProvideFault implementation:

public void ProvideFault(Exception error, MessageVersion version, ref Message fault) 
{        
        if (error is YourCustomException)
        {
            fault = Message.CreateMessage(version, string.Empty, String.Format("Error: {0}.", error.Message), new DataContractJsonSerializer(typeof(string)));
            fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));

            webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError);
        }
}

So when YourCustomException is thrown by business logic it will be catched by the handler and converted to proper fault.

See also: CodeProject article

Upvotes: 1

Related Questions