Solved

WCF - Error handling in service layer

Posted on 2014-11-05
4
52 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

Here I am going to explain creating proxies at runtime for WCF Service. So basically we use to generate proxies using Add Service Reference and then giving the Url of the WCF service then generate proxy files at client side. Ok, what if something ge…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

724 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