How to return JSON result from a custom exception filter? How to return JSON result from a custom exception filter? json json

How to return JSON result from a custom exception filter?


I found it possible to solve this problem using the code found in this article (with minor changes to it.)

public class HandleJsonExceptionAttribute : ActionFilterAttribute{    #region Instance Methods    public override void OnActionExecuted(ActionExecutedContext filterContext)    {        if (filterContext.Exception != null)        {            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;            filterContext.Result = new JsonResult()            {                JsonRequestBehavior = JsonRequestBehavior.AllowGet,                Data = new                {                    Error = filterContext.Exception.Message                }            };            filterContext.ExceptionHandled = true;        }    }    #endregion}


  public class YourController : BaseController    {        public JsonResult showcontent()        {            // your logic here to return foo json            return Json ( new { "dfd" }); // just a dummy return text replace it wil your code        }    }    public class BaseController : Controller    { // Catch block for all exceptions in your controller        protected override void OnException(ExceptionContext filterContext)        {            base.OnException(filterContext);            if (filterContext.Exception.Equals(typeof(ApplicationException)))            {                //do  json and return            }            else            {                // non applictaion exception// redirect to generic error controllor and error action which will return json result            }        }    }

Refer this link to see how to create and use HandleError attribute

*EDIT for HandleAttribute for Actions*

//not tested codepublic class HandleErrorfilter : HandleErrorAttribute    {         public string ErrorMessage { get; set; }        public override void OnException(ExceptionContext filterContext)        {                string message = string.Empty;                //if application exception                // do  something                 else                    message = "An error occured while attemting to perform the last action.  Sorry for the inconvenience.";            }            else            {                base.OnException(filterContext);            }        }      public class YourController : BaseController        {            [HandleErrorfilter]            public JsonResult showcontent()            {                // your logic here to return foo json                return Json ( new { "dfd" }); // just a dummy return text replace it wil your code            }        }