Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON result from a custom exception filter?

I would like to create a custom exception filter that will catch exceptions thrown in controller actions that return JSON results.

I would like to refactor the following action method:

        public JsonResult ShowContent()
    {
        try
        {
            // Do some business logic work that might throw a business logic exception ...
            //throw new ApplicationException("this is a business exception");

            var viewModel = new DialogModel
                                {
                                    FirstName = "John",
                                    LastName = "Doe"
                                };

            // Other exceptions that might happen:
            //throw new SqlException(...);
            //throw new OtherException(...);
            //throw new ArgumentException("this is an unhandeled exception");

            return
                Json(
                    new
                        {
                            Status = DialogResultStatusEnum.Success.ToString(),
                            Page = this.RenderPartialViewToString("ShowContent", viewModel)
                        });
        }
        catch (ApplicationException exception)
        {
            return Json(new { Status = DialogResultStatusEnum.Error.ToString(), Page = exception.Message });
        }
        catch (Exception exception)
        {
            return Json(new { Status = DialogResultStatusEnum.Exception.ToString(), Page = "<h2>PROBLEM!</h2>" });
        }
    }
}

What I would like to do is create a custom exception filter attribute that will catch any exceptions thrown in the action follow the following logic:

  1. Check if there was an exception
    • No: return
    • yes:
      • If BusinessLogic exception – return a JSON result
      • If other unhandled exception:
        • Log
        • Return another JSON result with a different result code
like image 202
Elie Avatar asked Mar 05 '11 17:03

Elie


1 Answers

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
}
like image 120
LaundroMatt Avatar answered Sep 28 '22 13:09

LaundroMatt