Skip to main content
 首页 » 编程设计

c#之如何忽略/跳过/处理 HttpWebResponse 错误并仍然将 JSON 返回给我的代码

2024年02月06日31qlqwjy

我正在尝试通过 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"; 
    } 
  } 
} 

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

I used Stripes "card_declined" test card number 4000000000000002

结果是 402 错误,具有以下 JSON 结构

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

由于返回 402 错误,这会破坏我的 C# 代码

System.Net.WebException: The remote server returned an error: (402) Payment Required. 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 获得的任何其他错误消息。

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

请您参考如下方法:

您可以使用以下异常处理程序

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" 
  } 
}