Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to handle error globally in asp.net web api

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 451
    Comment on it

    Hello All,

    Working with asp.net web api, we have multiple ways of handling error that is at controller level, method level we can use try and catch block and we can put our logic there to handle errors.

    But to handle error occurred any where in our web api, we can use global error handling method.


    I have the following block of code which will halp you to handle error globally in asp.net web api :


    public class ErrorHadler : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }        
            // Log error to the database
        }
    }
    


    Here we are creating a class called ErrorHandler which will inherit from ExceptionFilterAttribute. This ExceptionFilterAttribute class is present in System.Web.Http namespace and it has two methods present in it which are :

    1. public virtual void OnException(HttpActionExecutedContext actionExecutedContext);
    2. 2.public virtual Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken);


    we can use OnException by overriding method in our custom class and can create our custom response as well as we can put our logic for logging error to the database.

    Now we have to register our class in Global.aspx in Application_Start method:


    GlobalConfiguration.Configuration.Filters.Add(new ErrorHandler());
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: