如何在返回对象时抛出异常?

时间:2012-06-30 00:31:56

标签: c# exception

我有一个像这样的网络方法作为网络服务的一部分

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;
}

我想将错误处理合并到这里,这样如果没有返回行或drnull或者其他错误,我想以一个形式返回异常错误描述。但是,如果函数返回List<CustomObject>,当出现问题时,如何向客户端返回错误消息?

2 个答案:

答案 0 :(得分:4)

我将创建一个包装类,其中包含List CustomObject和{1}}错误信息作为另一个属性。

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

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

现在我将从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;    
}

编辑:为了使其更具可重用性和通用性,最好创建一个单独的类来处理这个问题。我将在我的Baseclass中将其作为属性

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;
}

答案 1 :(得分:0)

您使用的是WCF吗?如果是这样,请考虑使用faults