C# 在邮递员正文中捕获外部API错误消息
我使用以下代码来完成一个外部API调用C# 在邮递员正文中捕获外部API错误消息,c#,.net,api,error-handling,C#,.net,Api,Error Handling,我使用以下代码来完成一个外部API调用 WebResponse response = request.GetResponse(); string JSONResult = null; var data = response.GetResponseStream(); using (var reader = new StreamReader(data)) { JSONResult = reader.ReadToEnd(); } 当外部API出现异常时,reques
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'."
}
{
“消息”:“未找到与请求URI“/Foo”匹配的HTTP资源。”,
“MessageDetail”:“未找到与名为‘Foo’的控制器匹配的类型。”
}
虽然这在Fiddler和Postman中显示,但当它作为异常抛出时,我无法在任何地方获取此消息
当外部API调用发生错误时,如何获取此特定详细信息?您需要捕获异常,然后读取异常的响应流。读取异常的响应流与读取请求的响应是相同的。以下是如何:
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块中,因为您只是在尝试并捕获
请求。GetResponse()
。您的代码的其余部分需要跳出try-catch块,这样您就可以分别捕获该代码中的异常。try{}catch(Exception-ex){throw-ex}@AGrammerPro不幸的是,它需要做的工作比这多一些。看我的答案。@CodingYoshi我把你的答案投了高票:)