2013-03-28 43 views
2

我對web apis非常陌生,並且正在試驗一些api控制器異常。我的問題是,當拋出異常時,應用程序將返回太多的信息,其中包括堆棧跟蹤和返回的模型的一些屬性。我想知道是否返回的異常可以限制爲只是一個消息?.net web api異常錯誤的詳細信息

這裏有一個例子:

public IEnumerable<Appointments> GetAll(int id) 
{ 
    IEnumerable<Appointments> appointments = icdb.Appointments.Where(m => m.Id== id).AsEnumerable(); 
    return appointments; 
} 

而這是否會返回一個異常(DIFF問題),它將返回這樣的事情

{ 「消息」:「發生了錯誤。 「ExceptionMessage」:「 'ObjectContent`1'類型未能序列化響應正文 內容類型'application/json; charset = utf-8'。」,「ExceptionType」:「System.InvalidOperationException」, 「StackTrace」:null,「InnerException」:{「Message」:「一個 錯誤發生。「,」ExceptionMessage「:」自檢索循環 檢測屬性'UpdateBy'與類型 'System.Data.Entity.DynamicProxies.User_B23589FF57A33929EC37BAD9B6F0A5845239E9CDCEEEA24AECD060E17FB7F44C'。 路徑 '[0] .UpdateBy.UserProfile.UpdateBy.UserProfile'。「,」ExceptionType「:」Newtonsoft.Json.JsonSerializationException「,」StackTrace「:............... ................... : : :}

正如你注意到,它會返回與我的大多數模型的屬性的堆棧跟蹤。有沒有辦法在那裏時拋出一個異常,我可以只返回一個消息

回答

2

你剛纔提到,如果你遇到一個錯誤是這樣的,你有一個API電腦板,你應該做的事情:?

// a handled exception has occure so return an http status 
return Request.CreateResponse<string>(HttpStatusCode.BadRequest, your_message); 

因此,對於你給出的示例代碼,你可以有這樣的事情:

public IEnumerable<Appointments> GetAll(int id) 
{ 
    IEnumerable<Appointments> appointments= null; 
    try { 
     icdb.Appointments.Where(m => m.Id== id).AsEnumerable(); 
    } 
    catch { 
     var message = new HttpResponseMessage(HttpStatusCode.BadRequest); 
     message.Content = new StringContent("some custom message you want to return"); 
     throw new HttpResponseException(message); 
    } 
    return appointments; 
} 

如果控制器遇到一個未處理的異常調用代碼將收到一個500個狀態。

+0

噢很好,我不知道我可以回報! – gdubs 2013-03-28 05:29:49