向客户端显示异常消息

时间:2017-10-02 18:53:10

标签: javascript c# jquery asp.net asp.net-mvc

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

在Global.asax.cs文件中,我有全局应用程序错误处理程序:

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中获取异常消息,但它们都没有异常消息。

我的问题:我可以在Application_Error方法中执行哪些操作,以便我可以将exception.Message中包含的消息发送到全局ajaxError上客户端?请注意,我可以轻松处理在ajax请求命中的任何特定Action中发生的异常,但我想创建一个全局异常处理程序,这将允许我只是从我的应用程序的任何部分发出一条消息的异常,并在客户端向用户显示异常消息。

我尝试了this,但这并没有解决我的问题,因为我想使用jQuery全局ajaxError,而不是仅仅在特定的ajax请求中处理错误。可以修改它以实现我想要的吗?

1 个答案:

答案 0 :(得分:3)

您可以创建基本控制器并覆盖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"}});
        }
    }
}

并让所有控制器继承此

public class HomeController : BaseController
{

}

因此,只要控制器中发生异常,就会执行此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);               
    });

});
相关问题