C ා MVC global error processing in application ා error (including Ajax request)

Deal with global errors in global.asax application? Error of MVC.

If an error is reported before the request object is created, Context.Handler == null.

When judged to be an Ajax request, we return the Json object string. When not an Ajax request, go to the error display page.

/// <summary>
/// Global error
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
    Exception ex = Server.GetLastError();
    LogHelper.Error(ex); // Log errors( NLog It's very good.(* ̄︶ ̄))

    if (Context.Handler == null)

    if (new HttpRequestWrapper(Request).IsAjaxRequest())
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write("{\"state\":\"0\",\"msg\":\"" + ex.Message + "\"}");
        // Scheme 1 redirects to the error page with simple error information
        //string errurl = "/Error/Error?msg=" + ex.Message;
        //Response.Redirect(errurl, true);

        // Scheme 2 with error object, go to error page
        RouteData routeData = new RouteData();
        routeData.Values.Add("Controller", "Error"); // Existing error controller
        routeData.Values.Add("Action", "Error"); // Custom error page

        ErrorController controller = new ErrorController();
        HandleErrorInfo handleErrorInfo = new HandleErrorInfo(ex, "Error", "Error");
        controller.ViewData.Model = handleErrorInfo;
        ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(((MvcApplication)sender).Context), routeData));

The object usage of scheme 2 is the same as the default error page (i.e. / Shared/Error.cshtml). When we don't do anything with errors, we can configure the error page to / Shared/Error.cshtml in web.config.

Code of Error.cshtml:

@model System.Web.Mvc.HandleErrorInfo
    ViewBag.Title = "System error";
    Layout = "~/Views/Shared/_Layout.cshtml";

<h3 class="text-danger">System error</h3>
@if (Model != null)
    <span class="text-warning">@(Model.Exception.Message)</span>
    <span class="text-warning">An error occurred while processing the request.</span>

Action code of scheme 2:

public ActionResult Error()
    return View();

Keywords: ASP.NET JSON

Added by introvert on Thu, 09 Jan 2020 17:20:04 +0200