Solved

WCF - Error handling in service layer

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do ASP.NET and MVC work together? 4 32
Class object 2 28
SSL https .net web site force redirect 3 38
Error on link 14 40
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
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…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

863 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

19 Experts available now in Live!

Get 1:1 Help Now