Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle errors in method returning HttpWebResponse

Tags:

c#

I have this class that I can use to make a request to different paths with different Request methods(GET, POST etc).

I just added try and catch to log errors, however I don't know how to handle the catch block? I can't return an empty HttpWebResponse. "Not intended to be used directly from the code"

private static HttpWebResponse HttpRequest(string method, string path)
{
    try
    {
        var httpWebRequest =
            (HttpWebRequest) WebRequest.Create(ConfigurationManager.AppSettings["server"] + path);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = method;
        httpWebRequest.Credentials =
            new NetworkCredential(ConfigurationManager.AppSettings["username"],
                ConfigurationManager.AppSettings["password"]);
        httpWebRequest.PreAuthenticate = true;

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

Any ideas?

like image 757
Lord Vermillion Avatar asked Apr 16 '26 14:04

Lord Vermillion


1 Answers

Instead, you can return an HttpResponseMessage, and in a catch (Exception ex) return something like this:

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;

(With ContentType and Content set to suit your purposes)

like image 88
Richard Ev Avatar answered Apr 19 '26 04:04

Richard Ev