2016-09-23 42 views
1

在開發利用Web API的新Web應用程序時,我決定創建一組可容納事務結果的基本「響應」類是一個好習慣,在將來會有任何警告,錯誤或任何其他必要的數據。樣品下面:Web API將自定義異常對象轉換爲基本異常

public class VoidResultsVM 
{ 
    public bool IsSuccess { get; set; } 
    public List<string> Results { get; set; } 
    public List<Error> Errors { get; set; } 
    public List<Alert> Alerts { get; set; } 

    public VoidResultsVM() 
    { 
     Results = new List<string>(); 
     Errors = new List<Error>(); 
     Alerts = new List<Alert>(); 
    } 
} 

綁到該響應對象是從在.NET Exception類衍生自定義異常的對象的列表(「錯誤」)。這些類的主要好處是我們可以確切地確定發生錯誤的位置,並且可以向用戶添加自定義消息來解釋錯誤。下面的示例:

public class Error : Exception 
{ 
    //public Exception Exception { get; set; } 
    public string Origin { get; set; } 
    public string UserMessage {get; set;} 
    private DateTime timeStamp; 
    public DateTime TimeStamp { get { return timeStamp; } set { timeStamp = DateTime.Now; } } 
    public string Resolution { get; set; } 


    public Error(string msg, Exception ex, string origin, string usermessage, DateTime @timestamp, string resolution = "") 
     :base(msg, ex) 
    { 
     Origin = origin; 
     UserMessage = usermessage; 
     TimeStamp = @timestamp; 
     Resolution = resolution; 
    } 
} 

該對象已在開發和調試應用程序的後端是非常有用的,我希望保持這種儘可能。我正在運行的問題是,當嘗試通過幾個API操作時,如果其中一個「錯誤」對象返回,Web API(我相信)正在將該「錯誤」對象轉換爲其基類Exception。請參閱下面從API輸出的JSON:

{ 
    "IsSuccess": false, 
    "Results": [], 
    "Errors": [{ 
     "ClassName": "App.Models.Error", 
     "Message": "Error getting history", 
     "Data": { 

     }, 
     "InnerException": { 
      "ClassName": "System.Exception", 
      "Message": "No records found for criteria", 
      "Data": null, 
      "InnerException": null, 
      "HelpURL": null, 
      "StackTraceString": " at App.Database.DatabaseCore.GetHistory(HistorySearchVM history)", 
      "RemoteStackTraceString": null, 
      "RemoteStackIndex": 0, 
      "ExceptionMethod": "8\nGetShipmentHistory\nApp.Database, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\nApp.Database.DatabaseCore\nApp.Models.ViewModels.VoidResultsVM GetHistory(App.Models.ViewModels.HistorySearchVM)", 
      "HResult": -2146233088, 
      "Source": "App.Database", 
      "WatsonBuckets": null 
     }, 
     "HelpURL": null, 
     "StackTraceString": null, 
     "RemoteStackTraceString": null, 
     "RemoteStackIndex": 0, 
     "ExceptionMethod": null, 
     "HResult": -2146233088, 
     "Source": null, 
     "WatsonBuckets": null 
    }], 
    "Alerts": [] 
} 

所以我的問題是這樣的:我怎樣才能改變我的「錯誤」類,以便回發到時該Web API不將其轉換回基類客戶?這是甚至可以被覆蓋的東西嗎?

編輯

下面是從API控制器和數據庫的代碼來創建並返回此對象。有代碼中沒有邏輯錯誤對象轉換爲或從異常對象:

API控制器

public VoidResultsVM Search(SearchVM vm) 
    { 
     DatabaseCore db = new DatabaseCore(); 
     VoidResultsVM results = new VoidResultsVM(); 
     try 
     { 
      if (ModelState.IsValid) 
      { 
       results = db.GetRecordById(vm.Id); 
      } 
      else 
      { 
       throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); 
      }; 
     } 
     catch (Error) 
     { 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); 
     } 
     catch (Exception) 
     { 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); 
     } 
     db = null; 
     return results; 
    } 

數據庫

public Record GetRecordById(int id) 
    { 
     Record i = null; 
     using (var transactionScope = TransactionScopeBuilder.CreateReadCommitted()) 
     { 
      AppContext tempContext = null; 
      try 
      { 
       using (tempContext = new AppContext()) 
       { 
        i = tempContext.Records.Where(x => x.Id == id).FirstOrDefault(); 
       } 
      } 
      catch (Exception ex) 
      { 
       Common.Common.Log("", logName, Common.Common.LogLevels.ERROR, ex); 
       throw new Error(ex.Message, ex, "DATABASE", "", DateTime.Now); 
      } 
      finally 
      { 
       transactionScope.Complete(); 
      } 
     } 
     return i; 
    } 
+0

當你調試它是一個'錯誤'鍵入你的代碼一路?你能提供你實際返回/序列化響應的代碼嗎? – Wurd

+0

據我所知,只有返回信息是因爲您啓用了異常詳細信息。也許它不會轉換異常的標準屬性。看看[this](http://www.asp.net/web-api/overview/error-handling/exception-handling#exceptionfilters)並找到關於異常過濾器的部分。你有的例外是好的,但我會將其轉換爲錯誤消息模型。暴露API中的異常堆棧跟蹤通常是不好的做法。這應該只記錄在調試日誌中。 – Michael

回答

0

通過一些解決方案的工作後,我決定與邁克爾的建議一起返回一個專用視圖模型,該視圖模型包含調試使用最多的額外信息,並僅記錄完整的錯誤模型。