I have a controller, and a method as defined...
[HttpPost]
public ActionResult UpdateUser(UserInformation model){
// Instead of throwing exception
thr
This is a class I wrote the sends exceptions back to ajax requests as JSON
public class FormatExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult()
{
ContentType = "application/json",
Data = new
{
name = filterContext.Exception.GetType().Name,
message = filterContext.Exception.Message,
callstack = filterContext.Exception.StackTrace
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
else
{
base.OnException(filterContext);
}
}
}
It gets registered with MVC in your application's Global.asax.cs file like so:
GlobalFilters.Filters.Add(new FormatExceptionAttribute());
Best way I have found is as follows:
// Return error status and custom message as 'errorThrown' parameter of ajax request
return new HttpStatusCodeResult(400, "Ajax error test");
I use this Particular class for Ajax errors
public class HttpStatusCodeResultWithJson : JsonResult
{
private int _statusCode;
private string _description;
public HttpStatusCodeResultWithJson(int statusCode, string description = null)
{
_statusCode = statusCode;
_description = description;
}
public override void ExecuteResult(ControllerContext context)
{
var httpContext = context.HttpContext;
var response = httpContext.Response;
response.StatusCode = _statusCode;
response.StatusDescription = _description;
base.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.ExecuteResult(context);
}
}
Status code is a custom HTTP Status Code and in a global Ajax Error Function I test it like:
MyNsp.ErrorAjax = function (xhr, st, str) {
if (xhr.status == '418') {
MyNsp.UI.Message("Warning: session expired!");
return;
}
if (xhr.status == "419") {
MyNsp.UI.Message("Security Token Missing");
return;
}
var msg = 'Error: ' + (str ? str : xhr.statusText);
MyNsp.UI.Message('Error. - status:' + st + "(" + msg + ")");
return;
};
Based on what BigMike posted, this was what I did in my NON MVC/WEBAPI webproject.
Response.ContentType = "application/json";
Response.StatusCode = 400;
Response.Write (ex.Message);
For what it is worth (and thanks BigMike!) It worked perfectly.
What about returning an object back to your page and analyse that in your ajax
callback.
[HttpPost]
public ActionResult UpdateUser(UserInformation model)
{
if (SomethingWentWrong)
return this.Json(new { success = false, message = "Uuups, something went wrong!" });
return this.Json(new { success=true, message=string.Empty});
}
jQuery
$.ajax({
url: "...",
success: function(data){
if (!data.success)
{
// do something to show the user something went wrong using data.message
} else {
// YES!
}
}
});
This is where HTTP status codes come into play. With Ajax you will be able to handle them accordingly.
[HttpPost]
public ActionResult UpdateUser(UserInformation model){
if (!UserIsAuthorized())
return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
if (!model.IsValid)
return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
// etc.
}
Here's a list of the defined status codes.