1. Application_Error

namespace Libaray.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
LogHelper.LoadConfig(Server.MapPath("~/Web.config"));
//log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
}

protected void Application_Error(object sender, EventArgs e)
{
var lastError = Server.GetLastError();
if (lastError != null)
{
var httpError = lastError as HttpException;
if (httpError != null)
{
//Server.ClearError();
switch (httpError.GetHttpCode())
{
case 404:
Response.Redirect("/Exception/NotFound");
break;
}
}
}
}
}
}

2. 自定义的Exception处理

1) 注册

using System.Web;
using System.Web.Mvc;

namespace Libaray.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Libaray.Web.LibAttri.LogExceptionAttribute(), 1);
filters.Add(new HandleErrorAttribute(),2);
}
}

}

2)定义类

namespace Libaray.Web.LibAttri

{
public class LogExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
string broser = request.Browser.Browser;
string broserVersion = request.Browser.Version;
string system = request.Browser.Platform;
//string sMessage = filterContext.Exception.Message;

string sMessage = string.Format("消息类型:{0},消息内容:{1}, 引发异常的方法:{2}, 引发异常源:{3}",
filterContext.Exception.GetType().Name,
filterContext.Exception.InnerException.Message,
filterContext.Exception.TargetSite,
filterContext.Exception.Source +
filterContext.Exception.StackTrace);

string errBaseInfo = string.Format("UserId={0},Broser={1},BroserVersion={2},System={3},Controller={4},Action={5},Error={6}", "", broser, broserVersion, system, controllerName, actionName,sMessage);

LogHelper.Error(errBaseInfo);
filterContext.Controller.TempData["ExceptionMessage"] = sMessage;
filterContext.Result = new RedirectResult("/Exception/Error");

}
}
}

3. Exception Controller

namespace Libaray.Web.Controllers
{
public class ExceptionController : Controller
{

public ActionResult NotFound()
{
return View();
}

public ActionResult Error()
{
ViewBag.Error = TempData["ExceptionMessage"];
return View();
}
}
}

4. View

@{
ViewBag.Title = "Error";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row" style="margin-top:10px;">
<div class="col-sm-5">

<h3>错误</h3>
<div class="alert alert-info">
<p>对不起,访问出现错误。</p>
</div>

<a href="/Home/Index" class="btn btn-sm btn-primary">返回首页</a>
</div>

</div>

@{
ViewBag.Title = "访问出错";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row" style="margin-top:10px;">
<div class="col-sm-5">

<h3>访问资源出错</h3>
<div class="alert alert-info">
<p>对不起,我们无法找到指定页面,请确认访问地址是否输入正确。</p>
</div>

<a href="/Home/Index" class="btn btn-sm btn-primary">返回首页</a>
</div>

</div>

5. Webconfig

<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<customErrors mode="On">

</customErrors>
</system.web>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Libaray.Web
{
public class LogHelper
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public static void LoadConfig(string path)
{
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(path));
} /// <summary>
/// 错误信息
/// </summary
public static void Error(string error)
{
log.Error(error);
} /// <summary>
/// 致命信息
/// </summary>
public static void Fatal(string fatal)
{
log.Fatal(fatal);
} /// <summary>
/// 一般信息
/// </summary>
public static void Info(string info)
{
log.Info(info);
} /// <summary>
/// 警告信息
/// </summary>
public static void Warn(string warn)
{
log.Warn(warn);
}
}
}

MVC 自定义错误处理的更多相关文章

  1. ASP.net MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  2. MVC自定义错误页404静态页

    昨天公司要求给所有项目添加自定义404错误页,具体的要求实现的有以下几点: 1.实现自定义错误(如各种error,404等)跳转到指定的页面 2.所指定的页面输出的http状态值必须是404或其他指定 ...

  3. ASP.NET MVC 自定义错误页面心得

    自定义错误页面的目的,就是为了能让程序在出现错误/异常的时候,能够有较好的显示体验. 所以,首先要先了解,我们可以在哪里捕获异常. 当程序发生错误的时候,我们可以在两个地方捕获: Global里面的A ...

  4. 在ASP.NET MVC自定义错误页面

    异常处理跳转页面 第一步,在项目的Web.config文件中找到节点<system.web> 在此节点下添加配置(Error为定义的控制器也可以多添加些error标签用于区分不同的错误) ...

  5. MVC 自定义 错误页面

    很多时候,我们需要自定义错误页面,用来当发生异常后引导用户进入一个比较友好的错误页面. 在这里,我归结一下我常用的2个方案 1   通过Global.asax 文件来处理异常信息(这个不管是 MVC ...

  6. .NET MVC自定义错误处理页面的方法

    在ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAttribute特性,那 ...

  7. MVC自定义错误页面

    MVC异常处理主要有三种方案:1.基于HandleErrorAttribute重写OnException方法:2.基于Global.apsx添加Application_Error方法:3.直接在Web ...

  8. MVC自定义错误日志异常处理

    MVC添加错误日志处理模块很简单,只要写个继承自HandleErrorAttribute的过滤器,重新OnException方法,贴个异常处理代码如下: public class ExceptionA ...

  9. Asp.net MVC 自定义错误页面以及return HttpNotFound遇到的问题

    今天在处理mvc 项目404和500页面时,发现我以前比较喜欢用的Return HttpNotFound()没有跳转到我在webconfig中配置的自定义404页面,而且也不会去执行Global中的A ...

随机推荐

  1. logstash tomcat catalina.out 告警

    <pre name="code" class="html">[elk@dr-mysql01 tomcat]$ cat logstash_tomcat ...

  2. UML--对象的介绍

    UML相对于学习UML的符号含义而言,掌握它们背后的方法和思想是更为重要的.软件是一种实践知识,仅仅靠书本不可能成为高手.书本只能给出思路和知识点,而掌握和消化这些知识则必须在实践中去完成. 如果我们 ...

  3. java.lang.ClassNotFoundException错误原因汇总

    开发java很长时间了,还经常会遇到java.lang.ClassNotFoundException这样的错误,最近又处理了一次,起初怀疑是jdk版本比class文件的编译版本低了导致了,但是运维人员 ...

  4. cf413E Maze 2D

    E. Maze 2D time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...

  5. eucMenu

  6. phpcms:六、频道页(category.html)

    1.当前栏目的ID:{$catid}标题样式:{title_style($v[style])}(在添加内容或编辑内容的时候,标题右边 有一个选择颜色的块).{str_cut(strip_tags($v ...

  7. maven编写主代码与测试代码

    3.2 编写主代码 项目主代码和测试代码不同,项目的主代码会被打包到最终的构件中(比如jar),而测试代码只在运行测试时用到,不会被打包.默认情况下,Maven假设项目主代码位于src/main/ja ...

  8. jsf标签,jsp标签与jstl标签

    JSF通过定制标签与JSP集成.之前展示过的所有 JSF标签,<h:inputText>.<h:outputText>.<h:form> 和<f:view&g ...

  9. Hadoop,HBase集群环境搭建的问题集锦(四)

    21.Schema.xml和solrconfig.xml配置文件里參数说明: 參考资料:http://www.hipony.com/post-610.html 22.执行时报错: 23., /comm ...

  10. [Angular 2] Injecting a Service

    Using Services in Angular 2 is very simple. This lesson covers how to create a simple class as a Ser ...