How can I throw an exception when returning objects?

I have a web method like this as part of a web service

public List<CustomObject> GetInformation() {
    List<CustomObject> cc = new List<CustomObject>();

    // Execute a SQL command
    dr = SQL.Execute(sql);

    if (dr != null) {
       while(dr.Read()) {
           CustomObject c = new CustomObject()
           c.Key = dr[0].ToString();
           c.Value = dr[1].ToString();
           c.Meta = dr[2].ToString();
           cc.Add(c);
       }
    }
    return cc;
}

I want to include error handling in this so that if the rows are not returned or if drthere is null, or if something is wrong, I want to return an exception in the form of an error description. However, if the function returns List<CustomObject>, how can I also return an error message to the client when something goes wrong?

+5
source share
2 answers

I will create a wrapper class that has both List CustomObjectand error information as another property.

public class MyCustomerInfo
{
  public List<CustomObject> CustomerList { set;get;}
  public string ErrorDetails { set;get;}

  public MyCustomerInfo()
  {
    if(CustomerList==null)
       CustomerList=new List<CustomObject>();  
  }
}

Now I will return an object of this class from my method

public MyCustomerInfo GetCustomerDetails()
{
  var customerInfo=new MyCustomerInfo();

  // Execute a SQL command
    try
    {
      dr = SQL.Execute(sql);

      if(dr != null) {
         while(dr.Read()) {
           CustomObject c = new CustomObject();
           c.Key = dr[0].ToString();
           c.Value = dr[1].ToString();
           c.Meta = dr[2].ToString();
           customerInfo.CustomerList.Add(c);
         }
      }
      else
      {
          customerInfo.ErrorDetails="No records found";
      } 
   }
   catch(Exception ex)
   {
       //Log the error in this layer also if you need it.
       customerInfo.ErrorDetails=ex.Message;
   }     
  return customerInfo;    
}

EDIT. , .

public class OperationStatus
{
  public bool IsSuccess { set;get;}
  public string ErrorMessage { set;get;}
  public string ErrorCode { set;get;}
  public string InnerException { set;get;}
}
public class BaseEntity
{
  public OperationStatus OperationStatus {set;get;}
  public BaseEntity()
  {
      if(OperationStatus==null)
         OperationStatus=new OperationStatus();
  } 
}

, .

   public MyCustomInfo : BaseEntity
   {
      public List<CustomObject> CustomerList { set;get;}
      //Your constructor logic to initialize property values
   } 

OperationStatus

public MyCustomInfo GetThatInfo()
{
    var thatObject=new MyCustomInfo();
    try
    {
       //Do something 
       thatObject.OperationStatus.IsSuccess=true;
    }
    catch(Exception ex)
    {
      thatObject.OperationStatus.ErrorMessage=ex.Message;
      thatObject.OperationStatus.InnerException =(ex.InnerException!=null)?ex.InnerException:"";
    }
    return thatObject;
}
+4

WCF? , .

0

All Articles