1

I am making an external API call in my system. If the user is not logged in code will generate a 404 error. I want to identify that error in my code. Is it possible? Error look like this enter image description here

And my Code is like this

    public string  ExecuteGetRequest()
    {
        try
        {
            _url = Qparams != null ? Utility.WEBAPI_ENDPOINT  + Type + "?" + Qparams : Utility.WEBAPI_ENDPOINT + Type; ;
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(_url);

            if (!string.IsNullOrEmpty(SessionValues.UserID)&& !string.IsNullOrEmpty(SessionValues.AccessToken))
            {
                var handler = new HttpClientHandler();
                handler.Credentials = new NetworkCredential(SessionValues.UserID, SessionValues.AccessToken);
                string authInfo = SessionValues.UserID + ":" + SessionValues.AccessToken;
                authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                string username = SessionValues.UserID;
                String password = SessionValues.AccessToken;
                String encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
                httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);


            }
            httpWebRequest.Method = "GET";
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
            {
                _result = streamReader.ReadToEnd();
            }


        }
        catch (Exception ex)
        {
          Log.Add(LogTypes.Error,100, ex.ToString());

        }

        return _result;

    }
None
  • 5,582
  • 21
  • 85
  • 170

5 Answers5

2

Cast the exception to its actual type in order to get access to the WebResponse object. Then, cast that response object to HttpWebResponse in order to get the error code (and optionally, response content).

try
{
    // ...
}
catch ( WebException ex )
{
    var response = (HttpWebResponse) ex.Response;

    var errorCode = response.StatusCode;

    Log.Add(LogTypes.Error, errorCode, ex.Message);
}
Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
1

you can select each line while debugging and right click on that and click add watch option there, by this you can identify which line is producing error.

sheetal nainwal
  • 109
  • 1
  • 5
1

If you look at the screenshot you posted you can see that the actual exception class is a System.Net.WebException. WebException has a lot of useful properties, including the WebResponse. You can cast that response to a HttpWebResponse and then query its status code. What you can do is add a specialized exception handler for WebExceptions.

try
{
    // do your stuff
}
catch (WebException webEx)
{
    var response = webEx.Response as HttpWebResponse;

    if (response != null)
    {
       Log.Add(LogTypes.Error, 100, "HTTP StatusCode = " + (int)response.StatusCode);
    }
}
catch (Exception ex)
{
    Log.Add(LogTypes.Error, 100, ex.ToString());
}
Dirk
  • 10,668
  • 2
  • 35
  • 49
1

First of all you should usually only catch specific types of exception instead of a catch all like you have done here so I would have your catch block as:

catch (WebException ex)
{
    if (e.Status == WebExceptionStatus.ProtocolError) 
    {
         Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
         Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
     } 
}

Obviously instead of writing to console you can do whatever you want with StatusCode and Description.

TylerD87
  • 1,588
  • 11
  • 20
1

You can explore all the inner exceptions as

catch(Exception ex)
{
    string errorMessage = string.Empty;
    while (ex.InnerException != null)
    {
        errorMessage += ex.Message + Environment.NewLine;
        ex = ex.InnerException;
    }
    errorMessage += ex.Message + Environment.NewLine;
    MessageBox.Show(errorMessage);
}
Waqas Shabbir
  • 755
  • 1
  • 14
  • 34