Web API Exception Handling And Versioning Concepts

In this blog, we are going to learn about Web API Exception Handling and Versioning concepts. In interviews, many people are asked about Web API exception handling and version handling. Nowadays, both of these concepts have become common questions. Hope my blog will be helpful.
 
So, let us start.
 

Exception handling

 
First, we need to create one Web API solution. If you are a beginner, please refer to the below blog for creating a Web API solution.
After creating a Web API solution, you will get a default Home Controller and the Values API Controller.
 
Let’s first run the application and call "get a request" through postman. Let's call the Values Controller. Please check the below figure. This is the normal flow of execution and we are getting a proper result.
 
Web API Exception Handling And Versioning Concepts
 
Now, let’s make a change in the Get method. Here, I am going to throw an exception. Please check the below figure.
 
NotImplementedException means it initializes a new instance of the System.NotImplementedException class with a specified error message.
 
Web API Exception Handling And Versioning Concepts
 
After adding the throw new NotImplementedException(""); statement, please run your solution and call the values controller api/values method. As we know, it throws an exception. Please check the below figure.
 
Web API Exception Handling And Versioning Concepts
 
Avoiding the above situation, we need to handle the exception globally.
 
Please check the below figure. In my solution, I have created one folder and named it as "CustomHandler". Inside the folder, I have added one class named "GlobalExceptionHandler".
 
Web API Exception Handling And Versioning Concepts
 
For handling the exception globally, our GlobalExceptionHandler class is inheriting the properties of ExceptionHandler.
 
Implementation of the GlobalExceptionHandler class is shown below.
  1. using System.Net;  
  2. using System.Net.Http;  
  3. using System.Threading;  
  4. using System.Threading.Tasks;  
  5. using System.Web.Http;  
  6. using System.Web.Http.ExceptionHandling;  
  7. namespace WebApi_CustomeExceptoin_Verson.CustomHandler {  
  8.     public class GlobalExceptionHandler: ExceptionHandler {  
  9.         public override void Handle(ExceptionHandlerContext context) {  
  10.             var result = new HttpResponseMessage(HttpStatusCode.InternalServerError) {  
  11.                 Content = new StringContent("Internal Server Error Occurred"),  
  12.                     ReasonPhrase = "Custom Exception"  
  13.             };  
  14.             context.Result = new ErrorMessageResult(context.Request, result);  
  15.         }  
  16.         public class ErrorMessageResult: IHttpActionResult {  
  17.             private HttpRequestMessage _request;  
  18.             private readonly HttpResponseMessage _httpResponseMessage;  
  19.             public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage) {  
  20.                 _request = request;  
  21.                 _httpResponseMessage = httpResponseMessage;  
  22.             }  
  23.             public Task < HttpResponseMessage > ExecuteAsync(CancellationToken cancellationToken) {  
  24.                 return Task.FromResult(_httpResponseMessage);  
  25.             }  
  26.         }  
  27.     }  
  28. }  
In the above code, you can observe that we have one more class - ErrorMessageResult and inheriting the IHttpActionResult interface.
 
This class will have a Parameterized Constructor which takes 2 parameters,
  1. HttpRequestMessage
  2. HttpResponseMessage
We are going to assign this HttpResponseMessage to “context.Result”.
 
After handling the exception, next, we need to register this handler.
 
Now, we are going to register “GlobalExceptionHandler” in WebApiConfig class, such that any Web API exception can be handled globally. Please check the below figure. 
 
Web API Exception Handling And Versioning Concepts
 
After following the above steps, call the default Values Get method API through postman.
 
Please find the below figure. After throwing an exception, now we display a proper error message, not error stack trace to consumers. The below figure is expressing Get() method throwing exception. 
 
Web API Exception Handling And Versioning Concepts
 
But now we implemented an exception handling mechanism so we won't get any error stack trace. Instead of this, we get our custom message. Please observe the below figure.
 
Web API Exception Handling And Versioning Concepts
 
The conclusion is after throwing an exception. Now, we display a proper error message, not error stack trace, to the consumers.

API Versioning

 
The most important part of web apps is based on customer requirements we use to change rapidly. If we made some changes to API's those API's are consuming by customer's at the production environment will be breaking the application.solution for this is API Versioning.
 
Web API Exception Handling And Versioning Concepts
Let's implement API Versioning, please use the same web API solution, we can implement the API versioning in the same solution. Please go to manage NuGet package manager under the browse tab and search for the below NuGet package,
 
Microsoft.AspNet.WebApi.Versioning
 
Please find the below figure.
 
Web API Exception Handling And Versioning Concepts
 
After installing NuGet Package next, we are going to Register AddApiVersioning method in WebApiConfig.cs file.
 
The ApiVersioningOptions class allows you to configure, customize, and extend the default behaviors when you add an API versioning to your application.
 
The ApiVersioningOptions class has the following configuration settings,
  1. ApiVersionReader
  2. ApiVersionSelector
  3. DefaultApiVersion
  4. AssumeDefaultVersionWhenUnspecified
  5. ReportApiVersions
  6. Conventions
  7. ErrorResponses
  8. RouteConstraintName
I have referred from the below URL so please go through for more understanding. Here my motto is demonstrating programmatically, so I am not explaining more theory.
 
 
Please register the below code at WebApiConfig class file.
  1. config.AddApiVersioning(o =>  
  2. {  
  3.    o.ReportApiVersions = true;  
  4.    o.AssumeDefaultVersionWhenUnspecified = true;  
  5.    o.DefaultApiVersion = new ApiVersion(2, 0);  
  6.    o.ApiVersionReader = new HeaderApiVersionReader("version");  
  7.    o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);  
  8.    }  
  9. );  
Please check the below figure.
 
Web API Exception Handling And Versioning Concepts
 
Now, we implemented the API Versioning concept, so let's test it. Please add another API controller with the name “Values2Controller”.
 
After adding the Values2 to the API controller, next, we are going to add Route Attributes to both API controllers,  the old one and the new one. Please check the below figure.
 
Web API Exception Handling And Versioning Concepts
 
Now to call the API, we need to pass an API version from the header and the name of the header is “version”.
 
We are going to pass the header name “version” and value as 1.0 to the calling values controller.
 
Please check the below figure.
 
Web API Exception Handling And Versioning Concepts
 
After completing with calling version 1.0 values API, next, in the same way, we are going to call values2 API with version 2.0 header.
 
We are going to pass the header name “version” and value as 2.0 to the calling Values2 controller. Please find the below figure.
 
Web API Exception Handling And Versioning Concepts
 

SUMMARY

 
We covered practically.
  • Exception Handling 
  • API Versioning.
Please download the code from the below URL.