自定义错误处理程序

时间:2017-07-13 19:01:58

标签: c# error-handling asp.net-mvc-5

我在网上搜索并拼凑了一个不起作用的错误处理解决方案,主要是因为我不完全了解异常管道是如何工作的。我使用了不同的指南,但我没有得到任何主题为我工作。我希望错误处理程序做的是这个。我有一个名为workplanRepo的类,其中执行了所有查询。我用try和catch块覆盖了所有查询。我想要的是当发生错误时抛出异常,允许我为每个查询和默认异常消息自定义特定消息。然后,我希望能够在错误视图中检索异常处理程序已将用户重定向到的消息。我还想要一个捕获所有其他错误的默认处理程序。但不一定要有自定义消息部分。如果有人能解释或告诉我如何实现这一目标。我会很感激!。这是查询方法之一:

try {
    newItem["Author"] = _user.Id;
    newItem["Title"] = _user.Title; 

    newItem.Update();
    clientContext.ExecuteQuery();
    } 
    catch (Exception e) {
      throw new HttpException("Oops, there must have been an error: " + e.Message);
    }

1 个答案:

答案 0 :(得分:3)

在ASP.NET MVC 5中,我们可以在Global.asax.cs的 Application_Error事件 中捕获错误,而不是在每个查询中使用try catch块。从那时起重定向到自定义错误页面。

此外,我们还可以使用 Log4Net NLog 等日志框架。

例如,

    protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();

        LogException(exception);

        if (exception is HttpAntiForgeryException)
        {
            Response.Clear();
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;

            // Call target Controller and pass the routeData.
            IController controller = EngineContext.Current.Locator.GetInstance<CommonController>();

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Common");
            routeData.Values.Add("action", "AntiForgery");

            var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
            controller.Execute(requestContext);
        }
        else
        {
            // Process 404 HTTP errors
            var httpException = exception as HttpException;
            if (httpException != null && httpException.GetHttpCode() == 404)
            {
                Response.Clear();
                Server.ClearError();
                Response.TrySkipIisCustomErrors = true;

                // Call target Controller and pass the routeData.
                IController controller = EngineContext.Current.Locator.GetInstance<CommonController>();

                var routeData = new RouteData();
                routeData.Values.Add("controller", "Common");
                routeData.Values.Add("action", "PageNotFound");

                var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
                controller.Execute(requestContext);
            }
        }
    }

    private void LogException(Exception ex)
    {
        if (ex == null)
            return;

        // Ignore 404 HTTP errors
        var httpException = ex as HttpException;
        if (httpException != null &&
            httpException.GetHttpCode() == 404)
            return;

        try
        {
            // Log error message
        }
        catch (Exception)
        {
            // Don't throw new exception if occurs
        }
    }

您可以在GitHub查看使用Log4Net的示例项目。