2015-06-04 26 views
1

我試圖在web API中實現自定義錯誤處理, ,我需要從返回的HttpResponseMessage獲取異常。如何從Web API中的HttpResponseMessage獲取異常?

我試圖從得到的異常信息:

response.Content.ReadAsAsync<HttpError>().Result 

但我不能訪問結果對象,我發現了一個異常嘗試時, 所以我明明做錯了。

不知道如何去做, 援助將不勝感激。

編輯:

我的客戶端代碼是不相關的,它只是一個GET請求,服務器代碼:

控制器動作拋出異常:

if (condition == true) 
{ 
    var response = new HttpResponseMessage(HttpStatusCode.BadRequest) 
    { 
     Content = new StringContent("Some Exception Related Message"), 
     ReasonPhrase = "Some More Info" 
    }; 

    throw new HttpResponseException(response); 
} 
我實現DelegatingHandler的

SendAsync方法獲取響應, ,這是我想要獲取上面的控制器操作中引發的異常的調用堆棧。

errorDetails = new ResponseErrorDetailsFull 
{ 
    Message = "An error has occurred.", 
    ExceptionMessage = response.ReasonPhrase, 
    StackTrace = response.Content.ReadAsAsync<HttpError>().Result.StackTrace 
}; 

編輯#2

好了,我發現,如果我創建一個ExceptionFilterAttribute,並覆蓋onException的(),用我能夠訪問異常作爲中提到我的DelegatingHandler屬性上面的代碼。

有人可以提供解釋爲什麼這是這樣工作嗎?

+0

你嘗試過什麼?讀什麼? – Amit

+0

是的,我讀過,我需要從中獲取HTTPError對象並從那裏獲取堆棧跟蹤,但是當我嘗試提取它時,我得到異常,所以我顯然做錯了。 –

+0

你能顯示一些代碼嗎? –

回答

1

要在響應內容中獲得HttpError,您的服務器端API代碼需要將HttpError實例寫入響應流。

只有然後response.Content.ReadAsAsync<HttpError>().Result纔會產生該數據。

通常,如果服務器端代碼引發異常,則默認行爲是HTTP 500(內部服務器錯誤)狀態代碼,響應消息中沒有任何可分析的代碼。

如果發生HTTP 400(錯誤請求)或其他此類非500(非200)錯誤,通常會發迴響應數據。 (驗證錯誤等) 在這種情況下,您可能能夠從響應中讀取數據。

一般對任何錯誤的情況

,除非您的服務器端API代碼不寫一個已知類型到響應,您無法讀取它關閉對發送方的響應。

請張貼您的服務器端和客戶端代碼,以便我們進一步幫助您。

+0

增加了更多的代碼,您的參考將不勝感激。 –

+0

請參閱附加編輯#2 –

0

我發現這個博客有很好的例子: http://nodogmablog.bryanhogan.net/2016/07/getting-web-api-exception-details-from-a-httpresponsemessage/

我採用了一些更新的代碼:使用對象

if ((int)response.StatusCode >= 400) 
{ 
     exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(LogRequisicao.CorpoResposta); 
     LogRequisicao.CorpoResposta = exceptionResponse.ToString() ; 
     if (exceptionResponse.InnerException != null) 
      LogRequisicao.CorpoResposta += "\r\n InnerException: " + exceptionResponse.ToString(); 
} 

public class ExceptionResponse 
    { 
     public string Message { get; set; } 
     public string ExceptionMessage { get; set; } 
     public string ExceptionType { get; set; } 
     public string StackTrace { get; set; } 
     public ExceptionResponse InnerException { get; set; } 

     public override String ToString() 
     { 
      return "Message: " + Message + "\r\n " 
       + "ExceptionMessage: " + ExceptionMessage + "\r\n " 
       + "ExceptionType: " + ExceptionType + " \r\n " 
       + "StackTrace: " + StackTrace + " \r\n ";   
     } 
    } 
相關問題