0

I have the following code for accessing a Api which returns a Json value. Now it's possible that i try to access the api but nothing is being returned, aka the given ID its trying to search doesnt exist. This ofcourse returns a 404 but i do not know how to handle this error so the code continious on going, now it breaks the program and crashes.

public RootObject GetApi(string url)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try{
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream()){
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    var jsonReader = new JsonTextReader(reader);
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<RootObject>(jsonReader);
                }
            }

            catch (WebException ex){
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream()){
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

This is the button click event where the Url of the api is given.

 private void button1_Click(object sender, EventArgs e)
        {
            result_rTBox.Text = "";
            api_Handler api_Handler = new api_Handler();

            string spidyApi_itemSearch = "http://www.gw2spidy.com/api/v0.9/json/item-search/";
            string Gw2Api_allListings = "https://api.guildwars2.com/v2/commerce/listings/";


            string userInput_itemName = userSearchInput_tBox.Text;
            string spidyApi_searchIdByName = spidyApi_itemSearch + userInput_itemName;

            if (!string.IsNullOrWhiteSpace(userSearchInput_tBox.Text)){
                var spidyApi_searchIdByName_result = api_Handler.GetApi(spidyApi_searchIdByName);
                var Gw2Api_isItemIdinListing_result = api_Handler.GetApi(Gw2Api_allListings + spidyApi_searchIdByName_result.results[0].data_id);

                //result_rTBox.Text = Gw2Api_isItemIdinListing_result.results[0].data_id.ToString();
            }
}

First i access the api with string "spidApi_itemSearch" and after that I have and ID that i need to check if exists in the api Gw2Api_allListings. If it doesnt exist, which will happen quite often, it returns nothing with a 404 error. How do i get around of making the code continue even if it returns nothing?

EDIT: code that i have now, still crashes on the break.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                var requesting = WebRequest.Create(url);
                using (var response = request.GetResponse())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        var jsonReader = new JsonTextReader(reader);
                        var serializer = new JsonSerializer();
                        return serializer.Deserialize<RootObject>(jsonReader);
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound){

                    }

                }
                throw;
            }
        }

1 Answer 1

1

Use the HttpStatusCode Enumeration, specifically HttpStatusCode.NotFound

Instead of WebResponse, try using HttpWebResponse

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
  // handle the error here
}

Where we is a WebException

Sign up to request clarification or add additional context in comments.

7 Comments

I dont fully understand how to implement this. Do i have to replace the try catch with this if statement?
@KrijnvanderBurg Yes. You need to cast we.Response as an HttpWebResponse first.
i have edited my post with the new code, its still breaking on the throw as i do not know what to return as value, since there is nothing to return.
@KrijnvanderBurg you must send an empty RootObject as return value. And let the code which invokes the GetApi handle it. Remove the throw as I don't see any such use for it. You are better of handling the exception yourself.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.