Global error handling in the Global.asax Application_Error MVC's.
If the error when the request object creation yet to come, this time == Context.Handler null .
Ajax request when it is determined, we return Json string objects. When Ajax is not a request, go to the error page is displayed.
/// <Summary> /// the global error /// </ Summary> /// <param name = "SENDER"> </ param> /// <param name = "E"> </ param> protected void the Application_Error ( Object SENDER, EventArgs E) { Exception EX = the Server.GetLastError (); LogHelper.Error (EX); // log errors (NLog with very good (* ¯)¯)) IF (== Context.Handler null ) { return ; } IF ( new new HttpRequestWrapper (the Request) .IsAjaxRequest ()) { Response.Clear(); the Response.ContentType = " file application / JSON; charset = UTF-. 8 " ; Response.Write ( " {\" State \ ": \" 0 \ ", \" MSG \ ": \" " + ex.Message + " \ "} " ); the Response.Flush (); Response.End (); } the else { // embodiment a redirected to an error page, take the simple error // String errurl = "? / error / error MSG =" + ex.Message; // Response.Redirect (errurl, to true); // Option II band error object, goes to the error page Response.Clear (); RouteData routeData = new RouteData(); routeData.Values.Add ( " the Controller " , " Error " ); // existing controller error routeData.Values.Add ( " Action " , " Error " ); // custom error pages Server.ClearError () ; ErrorController in Controller = new new ErrorController in (); HandleErrorInfo handleErrorInfo = new new HandleErrorInfo (EX, " Error " , " Error " ); the Controller.ViewData.Model = handleErrorInfo; ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(((MvcApplication)sender).Context), routeData)); } }
Option II which object usage, and the default error pages (ie /Shared/Error.cshtml) the same. When we do not deal with any errors in the web.config error page can be configured to /Shared/Error.cshtml.
Error.cshtml code:
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "系统错误"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h3 class="text-danger">系统错误</h3> @if (Model != null) { <span class="text-warning">@(Model.Exception.Message)</span> } else { <span class="text-warning">处理请求时出错。</span> }
Scheme II Action code:
public ActionResult Error() { return View(); }