如何从Request.CreateErrorResponse中检索异常消息? [英] How can I retrieve the exception message from Request.CreateErrorResponse?

查看:87
本文介绍了如何从Request.CreateErrorResponse中检索异常消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有以下代码:

I have this code in my controller:

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

在我的调用代码中,我想检索Exception或至少错误.我写了这段代码:

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;

objContent的类型为 HttpError ,所以我将其删除:

The objContent is of type HttpError, so I pulled that out:

HttpError error = objContent.Value as HttpError;

但是 error 似乎是一个具有一个值,键的字典:Message,ValueL发生了错误"

But error seems to be a Dictionary with one value, key: Message, ValueL "An error has occurred"

我看不到任何异常迹象.

I can't see any sign of the exception.

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

断言失败.

推荐答案

我使用了您的代码并重现了该问题.

I used your code and reproduced the problem.

我无法进入.NET代码来查看为什么吞下了 Exception 的原因,所以我看看了

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代码,并尝试了以下内容,以了解会发生什么情况.

I took the .NET code and doctored up the following to see what would happen.

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 .如果我将传递给上述 errorCreator bool 的值更改为 true .在检查 r 时,我可以看到更多细节.

When I inspect the value of r, I can't see the Exception. If I change the value of the bool passed to errorCreator above to true. I can see much more detail when inspecting r.

我对 Web Http 命名空间不太满意,因此您必须弄清楚如何将true传递给该 HttpError 从GH的源头开始.

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.

它不能直接回答问题,但希望它能为您指明正确的方向.

It doesn't directly answer the question, but hopefully it points you in the right direction.

这篇关于如何从Request.CreateErrorResponse中检索异常消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆