Solved

WCF - Error handling in service layer

Posted on 2014-11-05
4
30 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

831 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