How To Read API Exception In C#

In this article, we will learn about how we can read an API exception in C#.

The WebException class is thrown when an error occurs while accessing the API. It can check the Response property or the Status property of the exception to determine why the request failed and give a brief idea about the exception.

Syntax

try
{
    //API CALL
}
catch (WebException webex) { }

Example

Now, create a new project in ASP.NET Web Application and select the Web API framework when creating the project.

upload-file-using-web-api-in-asp-net-mvc-and-jquery-1

Open the HomeController.cs file and add the code in it.

using System.IO;
using System.Net;
using System.Web.Mvc;

namespace APIWebException.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            return View();
        }
        public string GetData()
        {
            string result = string.Empty;
            try
            {
                //Here, We are using wrong URL to generate an Exception.
                //The correct URL is : https://reqres.in/api/users/1
                string ParentURL = "https://reqres.in/users/1";
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(ParentURL);
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method = "GET";
                httpWebRequest.Accept = "*/*";
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
    }
}

The below part will read your exception in brief, so a user can identify why this exception actually occurs.

WebResponse errResp = webex.Response; 
using (Stream respStream = errResp.GetResponseStream()) { 
  StreamReader reader = new StreamReader(respStream);
  result = reader.ReadToEnd(); 
}

That’s it.

Output:

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories