MVC Rethrow - exception as JSON

I am calling a web service from my MVC view and want to use the jquery ajax error function when throwing exceptions.

I am trying to throw a user-generated exception from my MVC business layer into my view-level controller and reconstruct it as a json response.

I can successfully throw my custom exception, the problem is that it appears as an HTML representation. I saw ways to declare a custom error response, but I was hoping I could directly rebuild the exception as JSON.

Any ideas?

JavaScript:

$.ajax({ type: "POST", url: 'create', data: "{userDetails:" + JSON.stringify(details) + "}", contentType: "application/json; charset=utf-8", success: function (data) { data = data.d; redirectSuccess(); }, error: function(err) { //display thrown exception here } }); 

CS

 public JsonResult create(MyModel.New details) { try { Library.insert(details); return Json(true); } catch (Exception ex) { throw; } } 

Thanks in advance for your help!

+7
jquery c # asp.net-mvc
source share
2 answers

I have finished developing a suitable solution.

For those who want a similar answer to the question I asked, I made a special filter announcement. The main part of this is that the result of the filter is returned as JSON, but even then it will return with success in the ajax jQuery call because it returns a status of 200, which jquery ajax reads as success.

Jquery ajax reads any status outside 200 as an error, so you can see that I changed the status code to the own number that I created, and I will document it, and so jquery ajax sees the error and gives it an ajax error.

 public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { filterContext.HttpContext.Response.StatusCode = 11001; filterContext.ExceptionHandled = true; filterContext.Result = new JsonResult { Data = new { success = false, error = filterContext.Exception.ToString() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } 

To reference the current filter, you simply add an error handler attribute to the function, as shown in the first line below:

 [MyErrorHandler] public JsonResult create(MyModel.New details) { try { Library.insert(details); return Json(true); } catch (Exception ex) { return Json(ex.Message); } } 
+6
source share

I don't think this works the way you think you need to pass an exception to the interface as an answer.

 public JsonResult create(MyModel.New details) { try { Library.insert(details); return Json(true); } catch (Exception ex) { return Json(ex.Message); } } 

And then treat it with JS as a success.

 $.ajax({ type: "POST", url: 'create', data: "{userDetails:" + JSON.stringify(details) + "}", contentType: "application/json; charset=utf-8", success: function (data) { if (data.Message) { //display error }else{ data = data.d; redirectSuccess();} }, error: function(err) { //display thrown exception here } }); 
+3
source share

All Articles