ASP.NET MVC異常處理模塊簡單教程-ASP.NET教程實例推薦

來源:文萃谷 1.2W

異常處理是每個系統必不可少的一個重要部分,它可以讓我們的程序在發生錯誤時友好地提示、記錄錯誤信息,更重要的是不破壞正常的數據和影響系統運行。

ASP.NET MVC異常處理模塊簡單教程-ASP.NET教程實例推薦

在MVC中處理異常,相信開始很多人都是繼承HandleErrorAttribute,然後重寫OnException方法,加入自己的邏輯,例如將異常信息寫入日誌文件等。當然,這並沒有任何不妥,但良好的設計應該是場景驅動的,是動態和可配置的。

簡單地説,不同的場景有不同的需求,而我們的.程序需要更好的面對變化。當然,繼承HandleErrorAttribute也完全可以實現上面所説的,只不過這裏我不打算去擴展它,而是重新編寫一個模塊,並且可以與原有的HandleErrorAttribute共同使用。

下面讓我們一起來學習 MVC異常處理模塊編程實例吧!

  2.1 定義配置信息

從上面已經可以知道我們要做的事了,針對不同的異常,我們希望可以配置它的處理程序,錯誤頁等。如下一個配置:

<!--自定義異常配置-->

<settingException>

<exceptions>

<!--add優先級高於group-->

<add exception="wordErrorException"

view ="PasswordErrorView"

handler="wordErrorExceptionHandler"/>

<groups>

<!--group可以配置一種異常的view和handler-->

<group view="EmptyErrorView" handler="yExceptionHandler">

<add exception="NameEmptyException"/>

<add exception="lEmptyException"/>

</group>

</groups>

</exceptions>

</settingException>

其中,add 節點用於增加具體的異常,它的 exception 屬性是必須的,而view表示錯誤頁,handler表示具體處理程序,如果view和handler都沒有,異常將交給默認的HandleErrorAttribute處理。而group節點用於分組,例如上面的UserNameEmptyException和EmailEmptyException對應同一個處理程序和視圖。

程序會反射讀取這個配置信息,並創建相應的對象。我們把這個配置文件放到ig中,保證它可以隨時改隨時生效。

  2.2 異常信息包裝對象

這裏我們定義一個實體對象,對應上面的節點。如下:

public class ExceptionConfig

{

/// <summary>

/// 視圖

/// </summary>

public string View{get;set;}

/// <summary>

/// 異常對象

/// </summary>

public Exception Exception{get;set;}

/// <summary>

/// 異常處理程序

/// </summary>

public IExceptionHandler Handler{get;set;}

}

  2.3 定義Handler接口

上面我們説到,不同異常可能需要不同處理方式。這裏我們設計一個接口如下:

public interface IExceptionHandler

{

/// <summary>

/// 異常是否處理完成

/// </summary>

bool HasHandled{get;set;}

/// <summary>

/// 處理異常

/// </summary>

/// <param name="ex"></param>

void Handle(Exception ex);

}

各種異常處理程序只要實現該接口即可。

  2.3 實現IExceptionFilter

這是必須的。如下,實現IExceptionFilter接口,SettingExceptionProvider會根據異常對象類型從配置信息(緩存)獲取包裝對象。

public class SettingHandleErrorFilter : IExceptionFilter

{

public void OnException(ExceptionContext filterContext)

{

if(filterContext == null)

{

throw new ArgumentNullException("filterContext");

}

ExceptionConfig config = ainer[ype()];

if(config == null)

{

return;

}

if(ler != null)

{

//執行Handle方法

le(ption);

if (andled)

{

//異常已處理,不需要後續操作

ptionHandled = true;

return;

}

}

//否則,如果有定製頁面,則顯示

if(!llOrEmpty())

{

//這裏還可以擴展成實現IView的視圖

ViewResult view = new ViewResult();

Name = ;

lt = view;

ptionHandled = true;

return;

}

//否則將異常繼續傳遞

}

}

  2.4 讀取配置文件,創建異常信息包裝對象

這部分代碼比較多,事實上,你只要知道它是在讀取ig的自定義配置節點即可。SettingExceptionProvider用於提供容器對象。

public class SettingExceptionProvider

{

public static Dictionary<Type, ExceptionConfig> Container =

new Dictionary<Type, ExceptionConfig>();

static SettingExceptionProvider()

{

InitContainer();

}

//讀取配置信息,初始化容器

private static void InitContainer()

{

var section = ection("settingException") as SettingExceptionSection;

if(section == null)

{

return;

}

InitFromGroups(ps);

InitFromAddCollection(ollection);

}

private static void InitFromGroups(GroupCollection groups)

{

foreach (var group in <GroupElement>())

{

ExceptionConfig config = new ExceptionConfig();

= ;

ler = CreateHandler(ler);

foreach(var item in <AddElement>())

{

Exception ex = CreateException(ption);

ption = ex;

Container[ype()] = config;

}

}

}

private static void InitFromAddCollection(AddCollection collection)

{

foreach(var item in <AddElement>())

{

ExceptionConfig config = new ExceptionConfig();

= ;

ler = CreateHandler(ler);

ption = CreateException(ption);

Container[ype()] = config;

}

}

//根據完全限定名創建IExceptionHandler對象

private static IExceptionHandler CreateHandler(string fullName)

{

if(llOrEmpty(fullName))

{

return null;

}

Type type = ype(fullName);

return teInstance(type) as IExceptionHandler;

}

//根據完全限定名創建Exception對象

private static Exception CreateException(string fullName)

{

if(llOrEmpty(fullName))

{

return null;

}

Type type = ype(fullName);

return teInstance(type) as Exception;

}

}

以下是各個配置節點的信息:

settingExceptions節點:

/// <summary>

/// settingExceptions節點

/// </summary>

public class SettingExceptionSection : ConfigurationSection

{

[ConfigurationProperty("exceptions",IsRequired=true)]

public ExceptionsElement Exceptions

{

get

{

return (ExceptionsElement)base["exceptions"];

}

}

}

exceptions節點:

/// <summary>

/// exceptions節點

/// </summary>

public class ExceptionsElement : ConfigurationElement

{

private static readonly ConfigurationProperty _addProperty =

new ConfigurationProperty("", typeof(AddCollection), null, faultCollection);

[ConfigurationProperty("", IsDefaultCollection = true)]

public AddCollection AddCollection

{

get

{

return (AddCollection)base[_addProperty];

}

}

[ConfigurationProperty("groups")]

public GroupCollection Groups

{

get

{

return (GroupCollection)base["groups"];

}

}

}

熱門標籤