Popular Posts

Wednesday, October 19, 2016

mvc custom exception handler

custom error and message handling or global filters:

https://www.asp.net/web-api/overview/error-handling/exception-handling


Just a dirty example!!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mail;
using System.Web.Mvc;
using System.Web.Routing;

namespace KidsWear.Shop.Filters
{
    /// <summary>
    /// Handle all exception in application level.
    /// Deal with exceptions based on type.
    /// Note: only handles Controller related exceptions i.e 500 code
    /// </summary>
    public class ExceptionActionFilter : FilterAttribute, IExceptionFilter
    {

        public EmailSender Emailer { get; set; }

        public ExceptionActionFilter()
        {
            if (Emailer == null)
            {
                Emailer = new EmailSender();
            }
        }

        public void OnException(ExceptionContext filterContext)
        {
                    // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                HandleJasonException(filterContext);
            }

            // Handle the business exception
            if (filterContext.Exception is BusinessException)
            {
                HandleBusinessException(filterContext);
            }

            // Handle security exception
            else if (filterContext.Exception is FluentSecurity.PolicyViolationException)
            {
                HandleSecurityException(filterContext);
            }
            else
            {
                HandleUnExpectedExceptions(filterContext);
            }

            filterContext.ExceptionHandled = true;
        }

        private void HandleUnExpectedExceptions(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            // If all the other exceptions then show a friendly message and exception will be logged by Elmah
            var msg =
                "An error has happened. We appologise for any inconveniences...The system Administrator will be notified who will look at the issue and will resolve it ASAP....";
            var emailData = new EmailData().WithDefaults();
            emailData.Subject = filterContext.Exception.Message;
            emailData.Body = filterContext.Exception.StackTrace;
            filterContext.Controller.Notify(msg, NotificationType.Error);

            filterContext.Result = new RedirectToRouteResult(new
                System.Web.Routing.RouteValueDictionary(new
                {
                    Controller = "Error",
                    Action = "Index"
                }
                ));

            Emailer.SendEmail(emailData);
        }

        private static void HandleSecurityException(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            filterContext.Result = new RedirectToRouteResult(new
                System.Web.Routing.RouteValueDictionary(new
                {
                    Controller = "Account",
                    Action = "Login"
                }
                ));
        }

        private static void HandleBusinessException(ExceptionContext filterContext)
        {

            filterContext.Controller.Notify(filterContext.Exception.Message, NotificationType.Error);

            filterContext.Result = new ViewResult
            {
                ViewName = filterContext.RouteData.Values["action"].ToString(),
                TempData = filterContext.Controller.TempData,
                ViewData = filterContext.Controller.ViewData
            };
        }

        private static void HandleJasonException(ExceptionContext filterContext)
        {
            // Log the error using Elmah
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);

            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    error = true,
                    message = filterContext.Exception.Message
                }
            };
        }

    }

}

No comments:

Post a Comment