tvb108108
tvb108108

Reputation: 408

MVC OnException to return Json Result to Display Error Message

When an error occurs my OnException() is being fire and the error is being logged properly from my ajax call.

The issue is the errorMessage I am returning in the Json result is NOT displaying and result.data is "".

Can you see what I am doing wrong with my code?

        $.post("/Admin/CreateOrganization", createOrganizationModel)
        .done(function (data) {
            if (data.success) {                       
                //Everything is good 
            }
            else {
                swal(
                    'Failed to create organization.',
                    data.errorMessage,
                    'error'
                );
            }
        })
        .fail(function () {
            swal(
                'Failed to create organization. Please reload and try again',
                '',
                'error'
            );
        });

Here is my OnException:

        protected override void OnException(ExceptionContext filterContext)
    {
        // Log to database...

        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new { success = false, errorMessage = "An error has occurred." },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            base.OnException(filterContext);
        }
        else
        {
            Server.ClearError();

            RedirectToErrorView();
        }
    }

Upvotes: 2

Views: 705

Answers (1)

tvb108108
tvb108108

Reputation: 408

Answer:

I fixed it as I was posting this question.

I had "error" in my Data = ... instead of "errorMessage"

It is showing the errorMessage now in my sweet alert message box.

Upvotes: 2

Related Questions