MVC 自定义错误处理

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

 

转载于:https://www.cnblogs.com/VirtualMJ/p/5178021.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值