Showing posts with label MVC Error Handling. Show all posts
Showing posts with label MVC Error Handling. Show all posts

Wednesday, July 4, 2018

How to manage Global Level Exception's

We can handle the Global Level Exceptions by creating the custom exception filter in our application. To create custom exception filter do the following things.
1) Create a Class in the App_Start folder inherit the IExceptionFilter interface.
2) Override the OnException() method.
3)  Create the object of the System.Exception Class.

public class LogFilter : IExceptionFilter
    {
                public void OnException(ExceptionContext context)
        {
                    Exception ex = context.Exception;
            if (!(ex is HttpException)) //ignoring the file not found exception
            {              
             //Do your stuff.....!!!
            }
        }
    }

4) Register the new Custom Filter into the Filter.Config.cs

filters.Add(new LogFilter());

5) Register the filter in Global.asax.cs file.

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

Note*- For using this we must enable the custom exception in the Web.config file and use the [Handle Error] action filter on either on the controller or action method.

Handling Errors in MVC

We can handle the errors in the MVC application by just enabling the custom errors tab in the web.config file.
<customErrors mode="On" defaultRedirect="Error">
 This will only handle the Internal Server Error Exceptions like HTTP Status Code 500 and won't handle the HTTP Status Code Exceptions like 404,405 etc for that we need to do the following.
   <customErrors mode="On" defaultRedirect="Error">
      <error statusCode="404" redirect="Error/NotFound" />
    </customErrors>
Here Error is the Controller Name and NotFound is the name of the Action Method after that we need to set the [HandleError] action filter on either the Controller or the Action Method as per our requirement.

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...