Show exception message to client side

前端 未结 1 1109
情书的邮戳
情书的邮戳 2021-01-26 20:58

In my asp.net mvc application, I would like to show the user the error message that was used to throw an exception. The exception occurs in an ajax request. I have tried this:

相关标签:
1条回答
  • 2021-01-26 21:37

    You can create a basecontroller and override the OnException method

    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"}});
            }
        }
    }
    

    and have all your controllers inherit from this

    public class HomeController : BaseController
    {
    
    }
    

    So any time an exception happens in your controllers, this OnException method will be executed and if it is an ajax request, It returns a json response with the below structure

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

    and now in your javascript, wire up the global ajaxError event and you can read the response coming from server and parse it to a js object and then read the Message property

    $(document).ready(function() {
    
        $(document).ajaxError(function (event, request, settings) {           
            var d = JSON.parse(request.responseText);
            alert("Ajax error:"+d.Message);               
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题