简体   繁体   English

如何从Request.CreateErrorResponse检索异常消息?

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

I have this code in my controller: 我的控制器中有这个代码:

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

In my calling code, I want to retrieve the Exception or at least the error. 在我的调用代码中,我想要检索异常或至少是错误。 I wrote this code: 我写了这段代码:

ObjectContent objContent = response.Content as ObjectContent;

The objContent is of type HttpError , so I pulled that out: objContent的类型是HttpError ,所以我把它拉出来:

HttpError error = objContent.Value as HttpError;

But error seems to be a Dictionary with one value, key: Message, ValueL "An error has occurred" error似乎是一个带有一个值的字典,键:消息,ValueL“发生错误”

I can't see any sign of the exception. 我看不到任何异常的迹象。

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

The assertion fails. 断言失败了。

I used your code and reproduced the problem. 我使用了你的代码并重现了这个问题。

I wasn't able to step in to the .NET code to see why the Exception was being swallowed, so I had a look at the HttpRequestMessageExtensions source on GitHub and found that it passes the the Exception to a new HttpError object that is created from configuration (line 459). 我无法介入.NET代码以查看为什么吞下Exception ,所以我查看了GitHub上HttpRequestMessageExtensions源代码 ,发现它将Exception传递给一个新的HttpError对象,该对象是从配置(第459行)。

I took the .NET code and doctored up the following to see what would happen. 我接受了.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;    
}

When I inspect the value of r , I can't see the Exception . 当我检查r的值时,我看不到Exception If I change the value of the bool passed to errorCreator above to true . 如果我将传递给errorCreatorbool的值更改为true I can see much more detail when inspecting r . 检查r时我可以看到更多细节。

I'm not great with the Web or Http namespaces, so you'll have to figure out how to pass true to that HttpError from the source on GH. 我对WebHttp命名空间不太满意,所以你必须弄清楚如何从GH上的源传递真实的HttpError

It doesn't directly answer the question, but hopefully it points you in the right direction. 它没有直接回答这个问题,但希望它能指出你正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM