簡體   English   中英

如何從Web API中的HttpResponseMessage獲取異常?

[英]How to get the exception from HttpResponseMessage in web API?

我正在嘗試在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方法獲取響應,這就是我想要獲取上面控制器操作中拋出的異常的callstack的地方。

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

編輯#2

好的,所以我發現如果我創建一個ExceptionFilterAttribute和Override OnException(),請使用我的DelegatingHandler上的屬性,我可以訪問上面代碼中提到的異常。

有人可以解釋為什么這樣做?

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

只有那時response.Content.ReadAsAsync<HttpError>().Result將產生該數據。

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

在HTTP 400(錯誤請求)或其他此類非500(非200)錯誤的情況下,通常發送回響應數據。 (在這種情況下,驗證錯誤等),您可以從響應中讀取數據。

通常,對於任何錯誤情況,除非您的服務器端API代碼沒有在響應中寫入已知類型,否則您無法從調用者端的響應中讀取它。

請發布您的服務器端和客戶端代碼,以便我們為您提供進一步的幫助。

我發現這個博客的例子非常好: 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 ";           
        }  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM