Пример #1
0
        /// <summary>
        /// Throws a properly formated <see cref="BadRequestException"/> if the <see cref="ModelStateDictionary"/> isn't valid.
        ///     Does nothing when the <see cref="ModelStateDictionary"/> is valid.
        /// </summary>
        /// <param name="modelState">The <see cref="ModelStateDictionary"/> that we are validating.</param>
        public static void ThrowIfInvalid(this ModelStateDictionary modelState)
        {
            if (modelState.IsValid)
            {
                return;
            }

            var exception = new BadRequestException();

            foreach (var key in modelState.Keys)
            {
                foreach (var error in modelState[key].Errors.Where(e => !string.IsNullOrEmpty(e.ErrorMessage)))
                {
                    exception.Add(key, error.ErrorMessage);
                }

                foreach (var error in modelState[key].Errors.Where(e => e.Exception?.Message != null))
                {
                    exception.Add(key, error.Exception.Message);
                }
            }

            throw exception;
        }
Пример #2
0
        /// <summary>
        /// Throws if any of the lambda parameters fails the required <paramref name="condition"/>.
        ///     It will agreegate all errors in the same <see cref="BadRequestException"/>.
        /// </summary>
        /// <param name="condition">The condition <see cref="Func{String, Bool}"/> that is required to pass.</param>
        /// <param name="exceptionExpression">The lamdba used to add the parameter to the <see cref="BadRequestException"/>.</param>
        /// <param name="expressions">The list of lambdas with parameters.</param>
        public static void InternalAction([NotNull] Func <string, bool> condition, Expression <Action <BadRequestException, string> > exceptionExpression, params Expression <Func <string> >[] expressions)
        {
            BadRequestException exception = null;

            foreach (var expression in expressions)
            {
                if (!condition(expression.Compile().Invoke()))
                {
                    continue;
                }

                if (exception == null)
                {
                    exception = new BadRequestException();
                }

                exceptionExpression.Compile().Invoke(exception, GetMemberName(expression));
            }

            if (exception != null)
            {
                throw exception;
            }
        }