【问题标题】:How can I retrieve the exception message from Request.CreateErrorResponse?如何从 Request.CreateErrorResponse 中检索异常消息?
【发布时间】:2016-08-03 23:31:52
【问题描述】:

我的控制器中有这段代码:

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 似乎是一个字典,只有一个值,key: Message, ValueL "An error has occurred"

我看不到任何异常迹象。

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

断言失败。

【问题讨论】:

  • HttpError 具有属性ExceptionMessageInnerException。有人住吗?
  • 怕不是,都是null

标签: c# asp.net-web-api


【解决方案1】:

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

我无法进入 .NET 代码以查看为什么 Exception 被吞下,所以我查看了 HttpRequestMessageExtensions source on GitHub 并发现它将 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 的源代码中将 true 传递给 HttpError

它没有直接回答这个问题,但希望它能为您指明正确的方向。

【讨论】:

  • 非常感谢。我尝试了一些重载然后放弃了,只使用了return Request.CreateResponse(HttpStatusCode.InternalServerError, new Exception(myMessage));。这将反序列化为异常。我猜它在开发中被忽略了。
  • 这真的很奇怪。我不知道它是反序列化的,但很高兴你找到了一个可行的解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
相关资源
最近更新 更多