Skip to content

Exception handling in mvc 5

Surendra Kandira

Surendra Kandira

Asked Aug 24, 2015, 10:10 PM EDT1 answer
Share
LinkedInX
How  to  handling  exception in mvc 5 . If error will occurs  it is save in data base or another text file. after developer to identify which exception is occurs

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Surendra Kandira
    0
    Globle lavle exception handling in mvc 4/5

    Add in Global.asax

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//Explanation done

    App_start
    FilterConfig.cs

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {

    //filters.Add(new HandleErrorAttribute()
    // {
    // ExceptionType = typeof(DivideByZeroException),
    // View = "DivideError"
    // });
    //filters.Add(new HandleErrorAttribute()
    //{
    // ExceptionType = typeof(NotFiniteNumberException),
    // View = "NotFiniteError"
    //});
    //filters.Add(new HandleErrorAttribute());//ExceptionFilter
    filters.Add(new EmployeeExceptionFilter());
    filters.Add(new AuthorizeAttribute());
    }


    Add new folder in application
    Filters............

    EmployeeExceptionFilter.cs file create and manage code


    public class EmployeeExceptionFilter:HandleErrorAttribute
    {
    public override void OnException(ExceptionContext filterContext)
    {
    FileLogger logger = new FileLogger();
    logger.LogException(filterContext.Exception);


    base.OnException(filterContext);
    //
    //filterContext.Result = new ContentResult()
    //{
    // Content="Sorry for the Error"
    //};
    }
    }


    create a Logger folder to manage exception
    FileLogger.cs calss create

    public void LogException(Exception e)
    {
    File.WriteAllLines("C://Error//" + DateTime.Now.ToString("dd-MM-yyyy mm hh ss")+".txt",
    new string[]
    {
    "Message:"+e.Message,
    "Stacktrace:"+e.StackTrace
    });
    }
    0