C# 处理返回HttpWebResponse的方法中的错误

C# 处理返回HttpWebResponse的方法中的错误,c#,C#,我有一个类,我可以使用它向不同的路径发出请求,并使用不同的请求方法(GET、POST等) 我刚刚添加了try和catch来记录错误,但是我不知道如何处理catch块?我无法返回空的HttpWebResponse“不打算直接从代码中使用” 有什么想法吗?你可以重新抛出这个错误,把责任推到链条上 catch (Exception e) { Logger.Error(e, "HttpRequest error"); throw; } 或者您可以返回null catch (Except

我有一个类,我可以使用它向不同的路径发出请求,并使用不同的请求方法(GET、POST等)

我刚刚添加了
try
catch
来记录错误,但是我不知道如何处理catch块?我无法返回空的HttpWebResponse<代码>“不打算直接从代码中使用”


有什么想法吗?

你可以重新抛出这个错误,把责任推到链条上

catch (Exception e)
{
    Logger.Error(e, "HttpRequest error");
    throw;
}
或者您可以返回
null

catch (Exception e)
{
    Logger.Error(e, "HttpRequest error");
    return null;
}

不要捕获常规
异常
——而是捕获可能包含
响应的
Web异常
。否则,只需在记录错误后重新显示它

try
{
    ... make request
}
catch (WebException webExcp) 
{
    Logger.Error(webExcp, "HttpRequest error: " + webExcp.Status);
    if (webExcp.Status == WebExceptionStatus.ProtocolError) {
        return (HttpWebResponse)webExcp.Response;            
    }
    throw;
}
catch(Exception ex)
{
   // Other exception, not a WebException, you probably want to Log an throw
    Logger.Error(ex, "HttpRequest error"); 
   throw;
}

相反,您可以返回,并在
catch(Exception ex)
中返回如下内容:

var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
    Content = new StringContent(string.Join(
        Environment.NewLine,
        ex.GetType().FullName,
        ex.Message))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
(将
ContentType
Content
设置为适合您的目的)

var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
    Content = new StringContent(string.Join(
        Environment.NewLine,
        ex.GetType().FullName,
        ex.Message))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;