Introduction
In this article, we will define exception handling in the ASP.NET Web API.
- HttpResponseException
- Exception Filter
- Registering Exception Filters
- HttpError
HttpResponseException
It is a special type of exception. It throws an HTTP code as an exception that is defined in the exception constructor. In it the exception is converted into a HTTP response.
- public Detail GetDetail(int Id)
- {
- Detail item = reposite.Get(Id);
- if (val == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- return val;
- }
If there is an Id parameter not defined then it will return the response "NotFound".
We can create own response message for controlling the resoponse, and this message wille be included with the HttpResponseException.
- public Detail GetDetail(int Id)
- {
- Detail val = reposite.Get(Id);
- if (item == null)
- {
- var show = new HttpResponseMessage(HttpStatusCode.NotFound)
- {
- Con = new StringContent(string.Format("There is no Detail with Id {0}", Id)),
- Reason_Phrase = "Detail Id not defined"
- }
- throw new HttpResponseException(Show);
- }
- return val;
- }
Exception Filters:
If there is any Unhandled type exception generated that is not the HttpResponseException type Exception then the Exception filter is used to handle these exceptions. It is written using the Web API.
The "System.Web.Http.Filters.IExceptionFilter" interface and "System.Web.Http.ExceptionFilterAttribute" class are used.
- namespace hello.Filters
- {
- using System;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http.Filters;
- public class E_Filter : ExceptionFilterAttribute
- {
- public override void OnException(HttpActionExecutedContext cont)
- {
- if (cont.Exception is NotImplementedException)
- {
- cont.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
- }
- }
- }
- }
Registering Exception Filters
We register the exception in various ways that are as follows:
-
Globally
-
By Action
-
By Controller
Globally
When the exception is registered globally, first we need to create an instance of the GlobalConfiguration.Configuration.Filters.
- GlobalConfiguration.Configuration.Filters.Add(new hello.E_Filter());
If we are working on ASP.NET MVC 4 Application then we add the API configuration code in WebApiConfig.cs class that is located in the App_Start folder.
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- config.Filters.Add(new hello.E_Filter());
- }
- }
By Action:
We can also apply a filter for the specific action.
- public class DetailController : ApiController
- {
- [NotImplExceptionFilter]
- public contact GetContact(int id)
- {
- throw new NotImplementedException("method can not be implement");
- }
- }
By Controller
We can apply the filter on the all method of a controller.
- [NotImplExceptionFilter]
- public class DetailController : ApiController
- {
- }
HttpError
HttpError provides a way to show the error message.
- public class DetailController : ApiController
- {
- public HttpResponseMessage GetDetail(int Id)
- {
- Detail val = reposite.Get(Id);
- if (val == null)
- {
- var report = string.Format("Id of Detail = {0} ",Id);
- HttpError error = new HttpError(report);
- return Request.CreateResponse(HttpStatusCode.NotFound, error);
- }
- else
- {
- return Request.CreateResponse(HttpStatusCode.OK, val);
- }
- }
- }
We can also use the CreateErrorResponse instead of HttpError.
Let's see an example of CreateErrorResponse:
- public class DetailController : ApiController
- {
- public HttpResponseMessage GetDetail(int Id)
- {
- Detail val = reposite.Get(Id);
- if (val == null)
- {
- var report = string.Format("Id of Detail = {0} ",Id);
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, error);
- }
- else
- {
- return Request.CreateResponse(HttpStatusCode.OK, val);
- }
- }
- }
This is the description of exception handling.


md ameenPosted Apr 25, 2021, 1:34 AM EDT
Nice Article
Abirami SenthilPosted Jun 1, 2020, 12:47 PM EDT
For using Exception handler how the end point implementation will look like
Hoang MinhPosted Oct 30, 2019, 11:48 PM EDT
Hi guys, I have a Web API is running e.g: http://localhost:52237. It works as well while I call api e.g: http://localhost:52237/api/payment/registerpayment by http POST via postman tool with request and body. Then I've created a Web application. How can I capture any http request & response as well as postman tool?
Chittaranjan SwainPosted Oct 30, 2019, 4:55 AM EDT
Nice article....
Vittorio MorelliniPosted Aug 6, 2019, 1:38 AM EDT
Hello, the handler has to an ashx ?
Akshay DalviPosted Jul 25, 2019, 7:22 AM EDT
Appreciate your efforts. Thanks!
Prem KumarPosted Mar 15, 2019, 6:48 AM EDT
Worth reading. Great job Jignesh!
nitesh poddarPosted Dec 5, 2018, 11:25 PM EST
Very good sir :)
Sachith WickramaarachchiPosted Mar 5, 2018, 7:24 AM EST
Good article, thanks for share
Sudhir RaoPosted Feb 14, 2018, 6:34 AM EST
Very good article for getting started on the subject
amit khajuriaPosted Nov 11, 2017, 4:46 AM EST
Very nice Article, easy to understand
rupinder batraPosted Feb 28, 2017, 10:20 PM EST
Nice Article...easy to understand.
Kuppurasu NagarajTOP 100Posted Jun 6, 2016, 8:09 AM EDT
Nice Sharing..
Sonu ChaudharyPosted Jun 6, 2016, 5:53 AM EDT
good one...
Bhavik PatelPosted Jun 4, 2016, 7:24 PM EDT
nice
Ketak BhalsingPosted Jun 1, 2016, 8:44 PM EDT
Helpful information....
NitinPosted Jun 1, 2016, 7:39 PM EDT
Good work
Thiruppathi RPosted Jun 1, 2016, 6:19 PM EDT
Very Nice ...
Debasis SahaTOP 100Posted Jun 1, 2016, 10:07 AM EDT
Nice one..
Akshay PhadkePosted Jun 1, 2016, 9:33 AM EDT
Nice article buddy you should write more often :)