如何忽略/跳过/处理 HttpWebResponse 错误,但仍将 JSON 返回到我的代码中

本文关键字:返回 JSON 我的 代码 跳过 何忽略 处理 HttpWebResponse 错误 | 更新日期: 2023-09-27 18:30:42

我正在尝试通过 C# 及其 API 设置对 Stripe 的调用。我正在使用以下代码通过帖子向他们的 API 添加新卡,并使用 JSON 响应来确定下一步

(我试图去除所有不必要的东西)

public static string stripeAPIcall(string customerId, string parameters, string stripeApiKey) {
    using (var stripeAPI = new System.Net.WebClient())
    {
      try
      {
        // set credentials
        stripeAPI.Credentials = new System.Net.NetworkCredential(stripeApiKey, "");
        //Set Headers
        stripeAPI.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
        stripeAPI.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        return stripeAPI.UploadString("https://api.stripe.com/v1/customers/" + customerId + "/cards, parameters);
    }
    catch (WebException ex)
    {   
        return "error";
    }
  }
}

当成功时,这可以很好地创建卡片。但是,如果出现错误,例如

我使用了条纹"card_declined"测试卡号4000000000000002

结果是以下 JSON 结构的 402 错误

{
  "error": {
    "message": "Your card was declined.",
    "type": "card_error",
    "code": "card_declined"
  }
}

这炸毁了我的 C# 代码,因为 402 错误返回

System.Net.WebException:远程服务器返回错误:(402) 需要付款。 at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadString(Uri address, String method, String data) at System.Net.WebClient.UploadString(String address, String data) at ASP.StripeGlobalHelpers.stripeAPIcall(String url, String parameters, String stripeApiKey, Boolean post)

那么,如何忽略/跳过/处理 402 错误并仍然将 JSON 返回到我的应用程序?我希望能够告诉用户"您的卡被拒绝"或我可能从 stripe 收到的任何其他错误消息。

如果您需要更多信息,请告诉我。

如何忽略/跳过/处理 HttpWebResponse 错误,但仍将 JSON 返回到我的代码中

您可以使用

以下异常处理程序

catch (WebException ex)
{
    var response = ex.Response.GetResponseStream();
    return response == null ? null : new StreamReader(response).ReadToEnd();
}

这将返回例如

{
  "error": {
    "type": "invalid_request_error",
    "message": "Invalid API Key provided: ftw?!1"
  }
}