繁体   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