Solved

WCF - Error handling in service layer

Posted on 2014-11-05
4
17 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:
Tchuki 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:Tchuki
Tchuki 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now