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

Leg*_*end 5 c# exception

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

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;
}
Run Code Online (Sandbox Code Playgroud)

我想包括错误处理到这一点,以便如果没有行返回,或者drnull,或者如果遇到其他问题,我想在一个错误描述的形式返回例外.但是,如果函数返回List<CustomObject>,当出现问题时,如何向客户端返回错误消息?

Shy*_*yju 4

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

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

  public MyCustomerInfo()
  {
    if(CustomerList==null)
       CustomerList=new List<CustomObject>();  
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我将从我的方法中返回此类的对象

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;    
}
Run Code Online (Sandbox Code Playgroud)

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

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();
  } 
}
Run Code Online (Sandbox Code Playgroud)

并让参与事务的所有子实体继承自该基类。

   public MyCustomInfo : BaseEntity
   {
      public List<CustomObject> CustomerList { set;get;}
      //Your constructor logic to initialize property values
   } 
Run Code Online (Sandbox Code Playgroud)

现在,您可以从您的方法中根据需要设置 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;
}
Run Code Online (Sandbox Code Playgroud)