coson
coson

Reputation: 8679

ASP.NET MVC Exception Handling with AJAX/JSON

I have several methods in a controller that look like:

[HttpPost]
public ActionResult AddEditCommentToInvoice(string invoiceNumber, string comments)
{
    var response = new { success = true, msg = "Comment saved", statusMsg = "Comment saved" };

    try
    {
        var recordsModified = invoiceService.AddCommentsToInvoice(invoiceNumber, comments);
        Log.Info(recordsModified ? "Updated Comment" : "Did not update Comment");

    } catch (Exception ex) {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return Json(new {
            success = false,
            msg = "There is missing field data",
            statusMsg = ex.Message
        }, JsonRequestBehavior.AllowGet);
    }

    return Json(response, JsonRequestBehavior.AllowGet);
}

While this code works, I'm not comfortable with this approach because:

  1. Try/Catches are expensive
  2. The code catches System.Exception
  3. The code is ugly

Now I know that I can use OnException or the HandleError attribute.
I also did some research on ELMAH and this looks promising.

But I still want to return JSON via AJAX to my user to indicate whether the operation was a success or not.

So my question is, has anyone used any of the three methods (or specifically ELMAH) to return JSON via AJAX?

Upvotes: 3

Views: 127

Answers (1)

Brian Mains
Brian Mains

Reputation: 50728

I use another approach that's an approach that can be applied at the controller level or globally through GlobalFilters. In my MVC controllers, you could override OnActionExecuted method, and do this:

   protected override void OnActionExecuted(ActionExecutedContext filterContext)
   {
      if (filterContext.Exception != null)
      {
         filterContext.Result = Json(new { success = false });
         return;
      }

      base.OnActionExecuted(filterContext);
   }

This could also be done as an action filter attribute. You wouldn't need any exception handling in your controllers - if an exception occurs, then this is handled within the context of the result.

Upvotes: 2

Related Questions