Home > DeveloperSection > Forums > How to check error type in C#
Anurag Sharma
Anurag Sharma

Total Post:40

Points:280
Posted on    December-05-2014 10:15 PM

 ASP.Net C#  Error 
Ratings:


 3 Reply(s)
 732  View(s)
Rate this:

Hi Guys

I am making an external API call in my system. If the user is not logged in code will generate a 404 error

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;

    }

 

Thanks



Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    December-06-2014 4:47 AM

You need to know at code-time what exceptions to expect, in order to catch them accordingly. As Dimitrov stated, a SQLException is thrown when the connection to an SQL server fails, so catching that specifically is a good tactic.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);

}


Modified On Apr-04-2016 07:30:08 AM

Ashish Pandey

Total Post:128

Points:898
Posted on    December-06-2014 5:43 AM

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.


Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    December-06-2014 6:12 AM

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());

}


Don't want to miss updates? Please click the below button!

Follow MindStick