1) Create a filter attribute:
public class ClientErrorAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter { public void OnException(ExceptionContext filterContext) { var response = filterContext.RequestContext.HttpContext.Response; response.Write(filterContext.Exception.Message); response.ContentType = MediaTypeNames.Text.Plain; filterContext.ExceptionHandled = true; } }
2) Apply filter to controller/action
[ClientError] public class HomeController : Controller { }
3) Throw exceptions
[HttpGet] public JsonResult CheckLogin() { if (!User.IsLoggedIn) { throw new Exception("You are not authorised to perform this operation"); } }
4) Catch exceptions in jQuery
$.ajax({ type: "post", url: "/SomeController/SomeAction", success: function (data, text) { //... }, error: function (request, status, error) { alert(request.responseText); } });