error handling using web api

How to apply Error Handling in Web API’s

Published on : Mar 2, 2017

Category : General

Mohan Nagaraj

Author

Error handling refers to anticipation, detection, and resolution of programming, application, and communication errors. Specialized programs, called error handlers, are available for some applications. The best programs of this type forestall errors if possible, recover from them when they occur without terminating the application, or (if all else fails) gracefully terminate an affected application and save the error information to a log file.

Programming error is the one that can be prevented mostly. Such an error can occur in syntax or logic. Syntax errors, which are a typographical mistake or improper use of special character, are handled by rigorous proofreading. Logic errors, also called bugs, occur when executed code does not produce the expected or desired result. Logic errors are best handled by meticulous program debugging. This can be an ongoing process that involves, in addition to the traditional debugging routine, beta testing prior to official release and customer feedback after release.

You can download this article as a PDF document Download now.

Error Handling in ASP.Net Web API

ASP.Net Web API is a lightweight framework from Microsoft that can be used for building stateless RESTful services that run on HTTP. Exceptions are errors that occur at runtime, and exception handling is the technique of handling runtime errors in your application code. You should have a good idea of how you can handle exception in Web API and send out appropriate error codes and error messages from your Web API controller methods.

Creating a Web API project:

  1. Start Visual Studio ->File Menu -> Select New Project.
  1. Select Installed Templates -> expand the Visual C# . Under Visual C#  select Web. In the list of project templates, selectNET Web Application. Name the project “Errorhandlingpractise1” and click OK. error handling
  1. In the new ASP.NET Project  -> select the Web API Click OK.
  1. Add folder and code folder for to select Web API check box .net application projects
  2. click theView menu -> select Solution Explorer. In Solution Explorer -> right-click the Models folder. From the context menu, select Add then select Class.

MODEL CLASS:

product class files

Product class:

  • Create a Product class and add the properties, then inherit the interface.
  • Check the status code and response.
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace Errorhandlingpractise1.Models
{
    public class Product : IHttpActionResult
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
        public string ErrorMessage { get; set; }

        public HttpStatusCode StatusCode { get; set; }
        public Product Response { get; set; }

        public Product()
        {

        }

        public Product(HttpStatusCode statusCode, Product response)
        {
            this.StatusCode = statusCode;
            this.Response = response;
        }

        public HttpResponseMessage CreateResponse(HttpStatusCode statusCode, object 
                response)

        {
            HttpRequestMessage request = new HttpRequestMessage();    
           request.Properties.Add(System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey, 

    new HttpConfiguration());

            HttpResponseMessage httpResponse = request.CreateResponse(statusCode, response);

            return httpResponse;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            if (!string.IsNullOrEmpty(this.ErrorMessage))

                return Task.FromResult(CreateResponse(this.StatusCode, this.ErrorMessage));
                return Task.FromResult(CreateResponse(this.StatusCode, this.Response));
        }
    }
}

ADD CONTROLLER:

  1. In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.
[adrotate banner=”7″]

Note: I have used ASP.NET MVC, ASP is already Familiar with controllers. Web API controllers are similar to MVC controllers, but inherit the API Controller class instead of the controller class.

  1. Select Web API 2 Controller – Empty. Click Addweb application controller
  1. Add the controller -> Name “Product Controller” and then click Add solution explorer window
  1. Double click the Product controller and open the file.
You can download this article as a PDF document Download now.

DESCRIPTION:

Products are stored in a fixed array in the controller class. The controller defines two methods that return products:

  • The GetAllProductsmethod returns the entire list of products as an IEnumerable<Product>
  • The GetProductmethod looks up a single product by its Id.
  • The GetProduct method Check whether the Id is null or not. If the Id is null, throw the HttpResponseException and return the Id is not found the Httpstatuscode is 404.
  • Whether the condition is not null return the product and the Httpstatuscode is 200.

PRODUCT CONTROLLER:

using Errorhandlingpractise1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Errorhandlingpractise1.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Toys", Category = "Teady bear", Price = 100 },
            new Product { Id = 2, Name = "Watch", Category = "Fastrack", Price = 35.75M },
            new Product { Id = 3, Name = "Laptop", Category = "Dell", Price = 16.99M }
        };



        public IEnumerable&amp;lt;Product&amp;gt; GetAllProducts()        
        {
            return products;
        }

        public Product GetProduct(int id)
        {
            var product = products.FirstOrDefault(p =&amp;gt; p.Id == id);
            try
            {

                if (product == null)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(string.Format("No product with ID = {0}", id)),
                        ReasonPhrase = "Product ID Not Found"
                    };
                    throw new HttpResponseException(resp);
                
                                    }

                return new Product(HttpStatusCode.OK, product);

            }
            catch (Exception ex)
            {

                var response = new Product(HttpStatusCode.NotFound, product) { ErrorMessage = "Product ID Not Found" };
           
                return response;
            }  
        }
    }
}

Running the application:

What is Postman and how do I use it with Azure?

Postman is a REST Client that runs as an application inside the Chrome browser. It is very useful for interfacing with REST APIs such as those found in Azure. In the Chrome browser navigate to https://chrome.google.com/webstore then search for Postman and it will show as offered by www.getpostman.com. Click the Add to Chrome button to install the application into your browser. Click Add in the dialog displayed to confirm installation.

The Chrome App Launcher will be added to your Desktop and Taskbar. Select the App Launcher and click the Postman icon which will launch the application. You can then type in the various REST calls you wish to make using all the various REST verbs such as GET, POST, PUT etc.

If you wish to use this with Azure you need two pieces of information. Your Subscription ID and also a JWT (JSON Web Token which is an authorization token). The Subscription ID can be found by viewing the portal and browsing Subscriptions or using Get-Azure Subscription. To get the JWT you will need to run the PowerShell code below, making sure to change the adTenant to your tenant. This code is part of code I previously covered in FAQ http://windowsitpro.com/azure/communicate-azure-rest-powershell.

Controller URL
GetAllProducts http://localhost/Errorhandlingpractise1/api/Products

running postman

Controller Url
GetProduct http://localhost/Errorhandlingpractise1/api/Products/1

running postman

Controller Url
GetProduct http://localhost/Errorhandlingpractise1/api/Products/5

running postman

Conclusion:

ASP.Net Web API is a lightweight framework from Microsoft that can be used for building stateless RESTful services that run on HTTP, ASP.NET Web API supports fully functional exception handling to handle runtime errors,

We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database, in this case it makes sense to return a HttpNotFound 404 status instead of the regular 200 code. Exceptions are errors that occur at runtime, and exception handling is the technique of handling runtime errors in your application code. We can handle the exception in Web API and send out appropriate error codes and error messages from your Web API controller methods.

[adrotate banner=”4″]