扩展方法 --- 异常处理

扩展方法: 异常处理。async

一般咱们写异常常常在function内容添加Try catch..  在方法过多的时候这么写确实不是什么好办法。学习

介绍一下个人扩展处理。 可能你们都是这么用的。会用的路过就剋以了。 不会的能够学习一下。spa

扩展代码以下 :日志

public static class ExceptionHelper
    {
        /// <summary>
        /// Exes the try asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static async Task<T> ExTryAsync<T>(Func<Task<T>> fun, string errorMessage)
        {
            try
            {
                return fun().Result;
            }
            catch (Exception ex)
            {
                throw new Exception(errorMessage + "---->" + ex.Message);
            }
        }

        /// <summary>
        /// Exes the try.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static T ExTry<T>(Func<T> fun, string errorMessage)
        {
            try
            {
                return fun();
            }
            catch (Exception ex)
            {
                throw new Exception(errorMessage + "---->" + ex.Message);
            }
        }

        /// <summary>
        /// Exes the try.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun">The fun.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns></returns>
        public static T ExTry<T>(Func<T> fun, T defaultValue)
        {
            try
            {
                return fun();
            }
            catch (Exception ex)
            {
                LogWriter.Error(ex);
                return defaultValue;
            }
        }
    }

使用方法:code

    public string GetValue()
    {
        LogHelperExtensions.Info("Object -> GetValue ");
        var baseValue = new BaseValue { State = false, Value = null, ErrDes = "系统服务异常!" };
        return ExceptionHelper.ExTry(() =>
        {
            //本身的业务逻辑
            return baseValue;
        }, baseValue);
    }

能够看到 咱们经过异常扩展咱们能够将每个方法体内容处理日志信息。更好的维护了项目的异常管理。blog

服务级别产生了bug咱们也能够直接经过日志查询。string

 

多说句 微软的 Async 很不错!it

相关文章
相关标签/搜索