我試圖在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屬性上面的代碼。
有人可以提供解釋爲什麼這是這樣工作嗎?
你嘗試過什麼?讀什麼? – Amit
是的,我讀過,我需要從中獲取HTTPError對象並從那裏獲取堆棧跟蹤,但是當我嘗試提取它時,我得到異常,所以我顯然做錯了。 –
你能顯示一些代碼嗎? –