gpt4 book ai didi

c# - C#无法查看有关API响应的错误,仅抛出异常以尝试/捕获

转载 作者:行者123 更新时间:2023-12-03 08:16:43 24 4
gpt4 key购买 nike

我正在编写一个程序来检查凭证编号是否有效,并且发现很难从正在使用的REST API中提取错误消息。
C#对我来说像通常的VB.net一样是很新的东西,但是现在可以覆盖某人。
基本上,我有一个HttpWebReqestHttpWebResponse对象,使用下面的代码,我成功地发出了请求并得到了很好的响应。
当一切顺利时,就没有问题了,但是例如,如果凭单无效或网站无效,我应该得到答复,就像在 postman 中所做的那样,例如,参见下文。

{
"message": "The given data was invalid.",
"errors": {
"voucher_no": [
"Sorry, that voucher number is invalid."
]
}
}
相反,我被抛出带有异常的Try/Catch ..

Error Message Error 422 unprocessable entity,


没有进一步的细节或对象来检查上面的真实消息?
try
{
using (HttpWebResponse response = mywebrequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
// I am unable to get to this part of the Code to process the Error because Try/Catch is executed instead ...
}
else
{
Stream dataStream1 = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream1);
responseFromServer = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
msgbox = new MsgBox_UI("Error", "Web Server Returned an Error", "There is a problem with this Voucher. It may be Expired or invalid at this time.", 1, false, 28);
msgbox.ShowDialog();
break;
}
如果那里有人对我如何进行这项工作有任何想法,那将是很大的帮助。

最佳答案

首先,最好使用HttpClient类。
此代码应为您工作(如果不让我知道):

private async Task<string> GetExtensionToken()
{
string url = "https://YourApi.com";
try
{
var httpclient = new HttpClient();
using (HttpResponseMessage response = httpclient.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
string Is_Not_Valid = "invalid";
if (result.Contains(Is_Not_Valid))
{
string token = "Whatever you want to extract if error page" ;
return token;
}
else
{
string token = "Whatever you want to extract if succeeded" ; return token;
}
}
}
}
catch (Exception ex)
{
return "Error from catch ";
}
}
用法:
private async void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = await GetExtensionToken();
}

关于c# - C#无法查看有关API响应的错误,仅抛出异常以尝试/捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65774491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com