2012-10-07 26 views
1

我們使用「HttpResponseExpection」來引發異常消息。在例外情況下,嘗試顯示錯誤內容和ReasonPhrase,但它只顯示錯誤狀態代碼。 發佈我正在使用的代碼來顯示消息。MVC4 - 顯示關於錯誤的更多信息

   var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
       { 
        Content = new StringContent(string.Format("No Product with ID = {0}", id)), 
        ReasonPhrase = "Product ID Not Found", 
        StatusCode = HttpStatusCode.Forbidden 

       }; throw new HttpResponseException(resp); 

代碼從index.cshtml

function find() { 

     clearStatus(); 

     var id = $('#productId').val(); 

     $.getJSON(API_URL + id, 
     function (data) { 
      viewModel.Name(data.Name); 
      viewModel.Category(data.Category); 
      viewModel.Price(data.Price); 
     }) 
    .fail(
     function (jqXHR, textStatus, err) { 
      $('#status').html('Error: ' + err); 
     }); 

    } 

任何幫助非常感激,謝謝提前。

+1

我找不出你的問題是什麼。 –

回答

1

jqXHR對象的responseText屬性將包含錯誤信息(Content屬性):

.fail(function (jqXHR, textStatus, err) { 
    alert(jqXHR.responseText); 
}); 

如果你想獲得ReasonPhrase屬性然後使用err參數:

.fail(function (jqXHR, textStatus, err) { 
    alert(err); 
}); 

還要確保在您的API控制檯上使用正確的狀態代碼404(HttpStatusCode.NotFound)而不是403(HttpStatusCode.Forbidden) r:

var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
{ 
    Content = new StringContent(string.Format("No Product with ID = {0}", id)), 
    ReasonPhrase = "Product ID Not Found", 
    StatusCode = HttpStatusCode.Forbidden 
}; 
throw new HttpResponseException(resp);