Thursday, December 22, 2016

C# WCF WebOperationContext - best practice in error handling

Hi,

WebOperationContext is typically used in a WCF REST method so that method can access the incoming request and outgoing response.

(see: http://stackoverflow.com/questions/18747581/difference-between-weboperationcontext-current-and-httpcontext-current )


... in my projects I wrap OperationContract-ed methods with error handling. You can imagine that with a standard method like MessageWrapper which uses an Action or Function and implements the code in lambda-style in-line. The MessageWrapper handles the Exception handling and sets the Response ErrorCode (WebOperationContext.Current.OutgoingResponse.StatusCode) to 200 if everything is fine or to error if an exception occurred.

public T MessageWrapper(Func<T> action) where T : class{
  try 
    SetStatusOK(); 
    return action(); 
  } catch (Exception exc){
    SetStatusError(exc);
    return null;
}

public ReturnObject Operation() {
  MessageWrapper(()=> return new ReturnObject("some", "parameters"));
}

... here I would love to mention, that with Castle you can create interceptors where you don't have to put the MessageWrapper inside the business logic code. You can keep this as an aspect (AOP) which can be configured at startup.

And here one more thing that helped a lot me during development time. You can set additionally to the StatusCode also a StatusDescription which e.g.: is displayed in your browser of choice as an explanation for an error. So StatusDescription = exc.Message is simply gold!

kr,
Daniel

No comments: