簡體   English   中英

如何從Request.CreateErrorResponse檢索異常消息?

[英]How can I retrieve the exception message from Request.CreateErrorResponse?

我的控制器中有這個代碼:

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception("Your cat is too small"));

在我的調用代碼中,我想要檢索異常或至少是錯誤。 我寫了這段代碼:

ObjectContent objContent = response.Content as ObjectContent;

objContent的類型是HttpError ,所以我把它拉出來:

HttpError error = objContent.Value as HttpError;

error似乎是一個帶有一個值的字典,鍵:消息,ValueL“發生錯誤”

我看不到任何異常的跡象。

Assert.AreEqual("Your cat is too small", error["Message"]);

斷言失敗了。

我使用了你的代碼並重現了這個問題。

我無法介入.NET代碼以查看為什么吞下Exception ,所以我查看了GitHub上HttpRequestMessageExtensions源代碼 ,發現它將Exception傳遞給一個新的HttpError對象,該對象是從配置(第459行)。

我接受了.NET代碼並對以下內容進行了修改,看看會發生什么。

private static HttpResponseMessage Test()
{
    HttpRequestMessage request = new HttpRequestMessage();

    return Test2(HttpStatusCode.InternalServerError, new Exception("Your cat is adequately sized."));
}

public static HttpResponseMessage Test2(HttpStatusCode statusCode, Exception exception)
{
    return Test2(statusCode, includeErrorDetail => new HttpError(exception, includeErrorDetail));
}

private static HttpResponseMessage Test2(HttpStatusCode statusCode, Func< bool, HttpError > errorCreator)
{
    HttpError r = errorCreator(false);
    return null;    
}

當我檢查r的值時,我看不到Exception 如果我將傳遞給errorCreatorbool的值更改為true 檢查r時我可以看到更多細節。

我對WebHttp命名空間不太滿意,所以你必須弄清楚如何從GH上的源傳遞真實的HttpError

它沒有直接回答這個問題,但希望它能指出你正確的方向。

暫無
暫無

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

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