【问题标题】:How to read CreateErrorResponse custom message in exception如何在异常中读取 CreateErrorResponse 自定义消息
【发布时间】:2018-06-19 13:19:34
【问题描述】:

我在异常中看不到 CreateErrorResponse 消息。我将消息“无效参数”传递给ThrowResponseException 方法,但我无法在异常中读取它。

e.Response.RequestMessage 给出默认的详细信息,但我只需要阅读“无效参数”。

try
{
  If (!ValidString)
  { ThrowResponseException(HttpStatusCode.BadRequest, "Invalid Parameters");}
}
catch (HttpResponseException e)
{
    msg = " Status Code: " + e.Response.StatusCode.ToString();
}

private void ThrowResponseException(HttpStatusCode statusCode, string message)
{
    var errorResponse = Request.CreateErrorResponse(statusCode,message);
    throw new HttpResponseException(errorResponse);
}

【问题讨论】:

  • 如果我删除 catch 块,它看起来像它的工作。我将不得不将代码更改为 HttpResponseMessage message = new HttpResponseMessage(statusCode); message.Content = new StringContent(msg);抛出新的 HttpResponseException(message);

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


【解决方案1】:

我发现了类似的东西,他们将消息包装在一个新的异常中并将该异常传递到创建响应中。然后他们可以提取错误消息的文本。 How can I retrieve the exception message from Request.CreateErrorResponse?

return Request.CreateResponse(statusCode, new Exception(message));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2015-11-04
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多