【问题标题】:Catch External API Error Message as in Postman Body在 Postman 正文中捕获外部 API 错误消息
【发布时间】:2017-10-09 16:23:29
【问题描述】:

我正在使用以下代码来完成外部 API 调用。

  WebResponse response = request.GetResponse();

  string JSONResult = null;
  var data = response.GetResponseStream();
  using (var reader = new StreamReader(data))
  {
    JSONResult = reader.ReadToEnd();
  }

当外部 API 出现异常时,request.GetResponse 会抛出错误。但是,我无法获得显示的消息,例如

{
        "Message": "No HTTP resource was found that matches the request URI '<site>/Foo'.",
        "MessageDetail": "No type was found that matches the controller named 'Foo'."
 }

虽然这显示在 Fiddler 和 Postman 中,但当它作为异常抛出时,我无法在任何地方收到此消息。

当外部 API 调用出错时,我如何获取此特定详细信息?

【问题讨论】:

  • try { } catch (Exception ex) { throw ex }
  • @AGrammerPro 不幸的是,它需要比这更多的工作。看我的回答。
  • @CodingYoshi 我赞成你的回答:)

标签: c# .net api error-handling


【解决方案1】:

你需要捕获异常,然后读取异常的响应流。读取异常的响应流与读取请求的响应是一样的。方法如下:

WebRequest request = 
WebRequest.Create("http://...");
WebResponse response = null; 
try
{
    response = request.GetResponse();
}
catch (WebException webEx)
{
    if (webEx.Response != null)
    {
        using (var errorResponse = (HttpWebResponse)webEx.Response)
        {
            using (var reader = new StreamReader(errorResponse.GetResponseStream()))
            {
                string error = reader.ReadToEnd();
                // TODO: use JSON.net to parse this string
            }
        }
    }
}

不要将所有代码放在上面的 try 块中,因为您只是 try(ing) 和 catch(ing) request.GetResponse()。您的其余代码需要超出该 try catch 块,以便您可以分别从该代码中捕获异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2018-01-02
    • 2011-11-22
    • 2015-11-20
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多