Solved

WCF - Error handling in service layer

Posted on 2014-11-05
4
34 Views
Last Modified: 2016-06-23
Hi,

I am working on a WCF service and working on a exception handling.
I'd like to know the best practice for returning exception.

Option 1 :  use request/response pattern

public ServiceResponse MethodTest(ServiceRequest)
{
}

Class ServiceResponse
{
        ResponseObject;
        FaultException;
        ValidationError;
}

1. If there is any exception than faultexception object will contain the error and remaining 2 object will be null
2. If there is Business rule failure than ValidationError will have all the error and remaining 2 objects will be null
3. If it is sucess responseobject will contain the data

Option 2 : returning faultexception

public ResponseObject MethodTest(string)
{
}

1. If there is any exception than throw faultexception with error
2. If there is Business rule failure than throw faultexception with validationerror
3. If it is sucess return responseobject will contain the data


I am not able to decide between this 2 options, which option should I use , please suggest.

Thanks,
0
Comment
Question by:Y K
  • 2
4 Comments
 
LVL 14

Accepted Solution

by:
Vel Eous earned 500 total points
ID: 40424397
I would be more inclined to use your second option, for example:

public ResponseObject DoSomething(int x)
{
    var responseObject = new ResponseObject();
    try
    {
        // do some work
        responseObject.Property = "FooBar";
        // test some buisiness logic
        if (!Equals(x, 1)) // fail
        {
            throw new FaultException("Failed business rule.");
        }
    }
    catch (FaultException ex)
    {
        throw;
    }
    catch
    {
        throw new FaultException("Something went horribly wrong!");
    }
    return responseObject;
}

public class ResponseObject
{
    public string Property { get; set; }
}

try
{
    var ret = this.DoSomething(2);
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}

Open in new window

0
 

Author Comment

by:Y K
ID: 40424504
Hi Tchuki,

Thanks for your quick response.

Can you please let me know below

1. What is the benefits of using 2nd option.
2. how can I use to send multiple business rule validation error at once.

Thanks,
0
 
LVL 14

Assisted Solution

by:Vel Eous
Vel Eous earned 500 total points
ID: 40424706
My preference for the second option is that it feels more natural and standard than the first option, either your client gets an object in response (all is good) or an exception (something went wrong).

If you want to pass additional useful information over the wire aside from just a simple string (as per my previous example), you can make use of FaultException<TDetail>.

An example extending the previous to use FaultException<T>:

public ResponseObject DoSomething(int x)
{
    var responseObject = new ResponseObject();
    try
    {
        // do some work
        responseObject.Property = "FooBar";
        // test some buisiness logic
        if (!Equals(x, 1)) // fail
        {
            var error = new BusinessValidationError()
            {
                Message = "Failed business rule(s).",
                ValidationErrors = new List<string> { "Failed bussines rule A", "Failed business rule B"}
            };
            throw new FaultException<BusinessValidationError>(error);
        }
    }
    catch (FaultException ex)
    {
        throw;
    }
    catch
    {
        throw new FaultException("Something went horribly wrong!");
    }
    return responseObject;
}

public class ResponseObject
{
    public string Property { get; set; }
}

[DataContract]
public class BusinessValidationError
{
    [DataMember]
    public string Message { get; set; }
    [DataMember]
    public List<string> ValidationErrors { get; set; }
}

[ServiceContract]
public interface IBusinessService
{
    [OperationContract]
    [FaultContract(typeof (BusinessValidationError))]
    ResponseObject DoSomething(int x);
}

try
{
    var ret = this.DoSomething(2);
}
catch (FaultException<BusinessValidationError> ex)
{
    Debug.WriteLine(ex.Detail.Message);
    ex.Detail.ValidationErrors.ForEach(Debug.WriteLine);
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}

Open in new window

0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question