HOW TO CHECK ERROR TYPE IN C#

Anurag Sharma

Total Post:40

Points:280
Posted by  Anurag Sharma
C#  Error 
 1127  View(s)
Ratings:
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

  1. Monaj Singh

    Post:41

    Points:287
    Re: How to check error type in C#

    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
  1. Ashish Pandey

    Post:128

    Points:898
    Re: How to check error type in C#

    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.

  1. Jeet Verma

    Post:110

    Points:776
    Re: How to check error type in C#

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

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!