宣告:本方式及程式碼只使用與.NET Web API.
先建立類繼承ExceptionFilterAttribute型別並複寫OnException方法。
程式碼如下:
using System; using System.IO; using System.Net.Http; using System.Text; using System.Web.Http.Filters; using FrameWork.Common; using FrameWork.Common.Const; namespace FrameWork.Web.Handle { /// <summary> /// 處理錯誤資訊 /// </summary> public class ErrorHandleAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext filterContext) { // 錯誤處理 base.OnException(filterContext); var sb = new StringBuilder(); sb.AppendLine("引數:"+ GetExceptionMessage(filterContext)); sb.AppendLine("異常內容:"+ filterContext.Exception.ToJson()); Log4NetHelp.Error(sb.ToString()); filterContext.Response = GetResponse(sb.ToString()); } /// <summary> /// 處理錯誤資訊為方便開發人員閱讀的格式,包括介面地址以及引數 /// </summary> /// <param name="actionExecutedContext">異常內容</param> private string GetExceptionMessage(HttpActionExecutedContext actionExecutedContext) { var session = System.Web.HttpContext.Current.Session; var request = System.Web.HttpContext.Current.Request; var guid = Guid.NewGuid().ToString(); var task = actionExecutedContext.ActionContext.Request.Content.ReadAsStreamAsync(); var content = string.Empty; try { var sm = task.Result; if (sm != null) { sm.Seek(0, SeekOrigin.Begin); var len = (int)sm.Length; var inputByts = new byte[len]; sm.Read(inputByts, 0, len); sm.Close(); content = Encoding.UTF8.GetString(inputByts); sm.Close(); } } catch (Exception e) { return e.Message; } var sessionId = session == null ? "" : session.SessionID; var pars = string.Format("error: id = {3}; sessionId = {0}; url = {1}; contentType = {4}; content = {2};" , sessionId , request.RawUrl , content , guid , request.ContentType); return pars; } /// <summary> /// 處理錯誤資訊後執行的方法 /// </summary> /// <param name="mes">錯誤資訊</param> private HttpResponseMessage GetResponse(string mes) { return JsonHelper.ToJson(new { Info = CommonConst.FailStr, Message = mes, Msg = false, ResultCode = CommonConst.FailCode }); } } }
如何使用呢?
只需要在需要捕捉異常的控制器加上[ErrorHandle]即可。
例如:
[ErrorHandle] public abstract class AdminControllerBase : Controller { //程式碼邏輯 }
如果繼承AdminControllerBase或者帶有[ErrorHandle]特性的類和方法出現了錯誤,都會執行OnException方法。
可以在處理異常的方法裡面加上自己想要的邏輯處理。