向客户端显示exception消息

在我的asp.net mvc应用程序中,我想向用户显示用于抛出exception的错误消息。 ajax请求中发生exception。 我试过这个:

在Global.asax.cs文件中,我有全局应用程序error handling程序:

protected void Application_Error(object sender, EventArgs e) { Exception exception = System.Web.HttpContext.Current.Server.GetLastError(); // do something so that client side gets the value exception.Message // I have tried these, but no success HttpContext.Current.Response.StatusDescription = exception.Message; HttpContext.Current.Response.StatusCode = 1000; // custom status code } 

在javascript中,我有全局的ajaxError处理程序:

 $(document).ajaxError(function (xhr, props) { // show the message in the exception thrown on the server side }); 

我尝试使用props.statusTextprops.responseText在JavaScript中获取exception消息,但它们都没有exception消息。

我的问题:我可以在Application_Error方法中做什么,以便我可以将exception.Message包含的消息提供给客户端的全局ajaxError函数? 请注意,我可以轻松处理在ajax请求命中的任何特定Action中发生的exception,但我想创建一个全局exception处理程序,这将允许我只是从我的应用程序的任何部分发出一条消息的exception,并在客户端向用户显示exception消息。

我试过这个 ,但这并不能解决我的问题,因为我想使用jQuery global ajaxError ,而不是仅仅在特定的ajax请求中处理错误。 可以修改它来实现我想要的吗?

您可以创建一个basecontroller并覆盖OnException方法

 public class BaseController : Controller { protected override void OnException(ExceptionContext filterContext) { //your existing code to log errors here filterContext.ExceptionHandled = true; if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { Error = true, Message = filterContext.Exception.Message } }; filterContext.HttpContext.Response.StatusCode = 500; filterContext.ExceptionHandled = true; } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {{"controller", "Error"}, {"action", "Index"}}); } } } 

让你的所有控制器inheritance自己

 public class HomeController : BaseController { } 

因此,只要控制器中发生exception,就会执行此OnException方法,如果它是ajax请求,则返回具有以下结构的json响应

 { Error : true, Message : "The message from the exception caught" } 

现在在您的javascript中,连接全局ajaxError事件,您可以读取来自服务器的响应并将其解析为js对象,然后读取Message属性

 $(document).ready(function() { $(document).ajaxError(function (event, request, settings) { var d = JSON.parse(request.responseText); alert("Ajax error:"+d.Message); }); });