zoukankan      html  css  js  c++  java
  • MVC 异常处理机制

    方法一 :web.config配置文件的 system.web 接点下添加,若为On则不会将异常信息反馈到用户,而是友好的跳转到error.htm

        <customErrors mode="On" defaultRedirect="error.htm">
          <error statusCode="404" redirect="~/error/notfound"></error>
        </customErrors>

    方法二:在  FilterConfig.cs 中有 new HandleErrorAttribute() 这样一句话, 此类为微软默认已经有的异常处理类,但是是注释的,方法而的优先级比方法一高。

    方法三:自定义异常处理类

    此处需要注意的是,和方法二差别不大,就是实现IExceptionFilter借口中的OnException方法,可以认为做一些在异常后的后续处理。

    调用可以通过         

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {

                filters.Add(new CustomExceptionAttribute(), 1);
                filters.Add(new HandleErrorAttribute(), 2);//数字越小优先级越高。
            }

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

     

     

    namespace Web

    {

        public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter

        {

     

            public void OnException(ExceptionContext filterContext)

            {

                if (filterContext.ExceptionHandled == true)

                {

                    HttpException httpExce = filterContext.Exception as HttpException;

                    if (httpExce.GetHttpCode() != 500)//为什么要特别强调500 因为MVC处理HttpException的时候,如果为500 则会自动将其ExceptionHandled设置为true,那么我们就无法捕获异常

                    {

                        return;

                    }

                }

     

                HttpException httpException = filterContext.Exception as HttpException;

     

                if (httpException != null)

                {

                    filterContext.Controller.ViewBag.UrlReferrer = filterContext.HttpContext.Request.UrlReferrer;

                    if (httpException.GetHttpCode() == 404)

                    {

                        filterContext.HttpContext.Response.Redirect("~/home/notfound");

                    }

                    else if (httpException.GetHttpCode() == 500)

                    {

                        filterContext.HttpContext.Response.Redirect("~/home/internalError");

                    }

                }

                //写入日志 记录

                filterContext.ExceptionHandled = true;//设置异常已经处理

            }

        }

    }

  • 相关阅读:
    查询表中字段相同的记录的sql
    c++ builder调用htmlencode
    win7 64位下使用regsvr32注册activex dll
    在sql 2005里创建一个和sa一样权限的账号
    c++ builder 使用indy http调用webservice方法
    sql 2005创建只读帐号的另一种方法
    C#如何用Graphics画出一幅图表
    C#中字符串的处理
    SQL语句快速介绍
    C#如何开发扫雷游戏
  • 原文地址:https://www.cnblogs.com/yexinw/p/3971216.html
Copyright © 2011-2022 走看看