ASP.Net Core中使用枚举类而不是枚举的方法(3)

public class Enumeration : IComparable { private readonly int _value; private readonly string _displayName; protected Enumeration() { } protected Enumeration(int value, string displayName) { _value = value; _displayName = displayName; } public int Value { get { return _value; } } public string DisplayName { get { return _displayName; } } public override string ToString() { return DisplayName; } public static IEnumerable<T> GetAll<T>() where T : Enumeration, new() { var type = typeof(T); var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); foreach (var info in fields) { var instance = new T(); var locatedValue = info.GetValue(instance) as T; if (locatedValue != null) { yield return locatedValue; } } } public override bool Equals(object obj) { var otherValue = obj as Enumeration; if (otherValue == null) { return false; } var typeMatches = GetType().Equals(obj.GetType()); var valueMatches = _value.Equals(otherValue.Value); return typeMatches && valueMatches; } public override int GetHashCode() { return _value.GetHashCode(); } public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) { var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value); return absoluteDifference; } public static T FromValue<T>(int value) where T : Enumeration, new() { var matchingItem = parse<T, int>(value, "value", item => item.Value == value); return matchingItem; } public static T FromDisplayName<T>(string displayName) where T : Enumeration, new() { var matchingItem = parse<T, string>(displayName, "display name", item => item.DisplayName == displayName); return matchingItem; } private static T parse<T, K>(K value, string description, Func<T, bool> predicate) where T : Enumeration, new() { var matchingItem = GetAll<T>().FirstOrDefault(predicate); if (matchingItem == null) { var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T)); throw new ApplicationException(message); } return matchingItem; } public int CompareTo(object other) { return Value.CompareTo(((Enumeration)other).Value); } }

public class EmBusinessError : Enumeration, ICommonError { private int errCode; private String errMsg; public static readonly EmBusinessError parameterValidationError = new EmBusinessError(10001, "参数不合法"); private EmBusinessError() { throw new Exception("私有构造函数不能调用"); } private EmBusinessError(int value, string displayName) : base(value, displayName) { this.errCode = value; this.errMsg = displayName; } public int GetErrCode() { return this.errCode; } public string GetErrMsg() { return this.errMsg; } public void SetErrCode(int errCode) { this.errCode = errCode; } public ICommonError SetErrMsg(string errMsg) { this.errMsg = errMsg; return this; } }

//包装器业务异常类实现 public class BusinessException : Exception, ICommonError { private ICommonError commonError; //直接接收EmBusinessError的传参用于构造业务异常 public BusinessException(ICommonError commonError):base() { this.commonError = commonError; } public BusinessException(ICommonError commonError, string errMsg):base() { this.commonError = commonError; this.commonError.SetErrMsg(errMsg); } public int GetErrCode() { return this.commonError.GetErrCode(); } public string GetErrMsg() { return this.commonError.GetErrMsg(); } public ICommonError SetErrMsg(string errMsg) { this.commonError.SetErrMsg(errMsg); return this; } public ICommonError GetCommonError() { return commonError; } }

异常中间件:

public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; /// <summary> /// /// </summary> /// <param></param> public ExceptionHandlerMiddleWare(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; await WriteExceptionAsync(context, exception).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception exception) { var response = context.Response; response.ContentType = "application/json;charset=utf-8"; var result = new CommonReturnType(); if (exception is BusinessException) { var businessException = (BusinessException)exception; var errModel = new { errCode= businessException.GetErrCode(), errMsg= businessException.GetErrMsg() }; result = CommonReturnType.Create(errModel, "fail"); } await response.WriteAsync(JsonConvert.SerializeObject(new { data = result.GetData(), status = result.GetStatus() }) ).ConfigureAwait(false); } }

Response文件夹:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdswxg.html