ASP.NET MVC3 异常处理 摘抄

22 篇文章 0 订阅
18 篇文章 0 订阅

比较乱,参考文末链接

使用 handleError attribute 有以下局限:

1. Not support to log the exceptions  不支持exception记录
2. Doesn't catch HTTP exceptions other than 500   无法捕捉到500之外的http exception
3. Doesn't catch exceptions that are raised outside controllers    controller之外抛出的异常无法处理
4. Returns error view even for exceptions raised in AJAX calls      ajax调用出现exception时,会将错误页面内容返回


其他方法

重写Controller的OnException方法,其他继承自BaseController的Controller

 public class BaseController : Controller

  {
        protected override void OnException(ExceptionContext filterContext)
        {
            if(filtercontext==null)
            return ;
           var ex = filtercontext.exception??new exception("no further information exists");
           logger.logerror(ex,"error general onexceipton");
           filtercontext.exceptionhandled = true;
           var data = {
                      errormessage = httputility.htmlencode(ex.message),
                      theexception = ex,
                      showmessage = !(filtercontext.exception==null),
                      showlink = false;
                 };
             filtercontext.result = view("errorpage",data);
             //base.OnException(filterContext);
      } 

 }

2、创建FilterAttribute

通过FilterAttribute,并把它添加到全局过滤器集合中就可以提供给整个应用程序使用,如果只需要在某几个Action中使用,可以在Controller的Action中添加此特性。

 Filter定义如下:

 public class LogExceptionFilterAttribute : FilterAttribute, IExceptionFilter

{
    public void OnException(ExceptionContext filterContext)
    {
        // 添加记录日志代码
    }
}

如果要应用给所有的Controller的所有Action,在Global.asax.cs中实现下面代码即可:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)  {  
    filters.Add(new LogExceptionFilterAttribute()); 
    filters.Add(new HandleErrorAttribute());
 }

或者给只需要使用此特性的Controller或Action添加 : 

[LogExceptionFilter()] 
 public ActionResult About()  
{    
  throw new Exception("出错."); 
}
3  使用  Elmah


4   global.asax 中添加如下事件

protected void Application_Error()
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException;
    Response.Clear();
    Server.ClearError();
    var routeData = new RouteData();
    routeData.Values["controller"] = "Errors";
    routeData.Values["action"] = "General";
    routeData.Values["exception"] = exception;
    //httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500; 
    Response.StatusCode = 500;
    if (httpException != null)
    {
        Response.StatusCode = httpException.GetHttpCode();
        switch (Response.StatusCode)
        {
            case 403:
                routeData.Values["action"] = "Http403";
                break;
            case 404:
                routeData.Values["action"] = "Http404";
                break;
        }
    }           
    // Avoid IIS7 getting in the middle
    Response.TrySkipIisCustomErrors = true; 
    IController errorsController = new ErrorsController();
    HttpContextWrapper wrapper = new HttpContextWrapper(Context);
    var rc = new RequestContext(wrapper, routeData);
    errorsController.Execute(rc);
}

创建 ErrorController

public class ErrorsController : Controller
{
    public ActionResult General(Exception exception)
    {
        return View("Exception",exception);
    }

    public ActionResult Http404()
    {
        return View("404");
    }

    public ActionResult Http403()
    {
        return View("403");
    }
}

参考

http://blog.163.com/elgyin@126/blog/static/189426202011101510232757/

http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc

http://www.codeproject.com/Articles/422572/Exception-Handling-in-ASP-NET-MVC

http://www.cnblogs.com/TomXu/archive/2011/12/15/2285432.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值