【问题标题】:Show exception message to client side向客户端显示异常消息
【发布时间】:2017-10-02 18:53:10
【问题描述】:

在我的 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 请求命中的任何特定操作中发生的异常,但我想创建一个全局异常处理程序,这将允许我只使用来自应用程序任何部分的消息引发异常,异常消息会在客户端显示给用户。

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 我已经尝试了一些类似的代码,但没有成功。也许我没有以正确的方式使用它。 Anway,我有一个问题,有了这个代码,我需要摆脱 Global.asax 中的 Application_Error 吗?
    • 我不会使用 Global.asax。当您决定在未来的项目中使用 ASPNETcore 时,您将无法再使用它。但是,protected override void OnException(ExceptionContext filterContext){} 将是,并且在您的控制器中使用。
    猜你喜欢
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2011-11-03
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    相关资源
    最近更新 更多