public void Should_throw_a_validation_exception_if_validator_is_found_and_Request_is_invalid(
            IRequestHandler <Request, Response> validationHandler,
            Request invalidRequest,
            Container Container,
            Exception exception
            )
        {
            "Given an invalid Request"
            .Given(() => invalidRequest = new Request()
            {
                Name = null
            });

            "And a Container"
            .And(() => Container = new Container());

            "And an IValidator for the Request registered"
            .And(() => Container.Register <IValidator <Request>, RequestValidator>());

            "And a ValidationHandler constructed with the Container"
            .And(() => validationHandler = new ValidationHandler <Request, Response>(Container, new RequestHandler()));

            "When handling the invalid Request"
            .When(() => exception = Record.Exception(() => validationHandler.Handle(invalidRequest)));

            "A ValidationException should be thrown"
            .Then(() => exception.Should().BeOfType <ValidationException>());

            "And the error property should be 'Name'"
            .Then(() => exception.As <ValidationException>().Errors.Single().PropertyName.Should().Be("Name"));

            "And the error message should be 'Name cannot be null'"
            .Then(() => exception.As <ValidationException>().Errors.Single().ErrorMessage.Should().Be("Name cannot be null"));
        }
Esempio n. 2
0
        public void SetException(Exception exception)
        {
            if (exception.As <JsObject>().member("GetType") == null)
            {
                exception = new JsException(exception.As <JsError>());
            }
            Console.WriteLine(exception);  // We don't to forget about the exception, but the fact of the matter is
                                           // an async void method can't propagate the exception to the caller.
//            throw exception;
//            AsyncMethodBuilderCore.ThrowAsync(exception);
        }
Esempio n. 3
0
        public static string GetDebugResponse(this Exception exception, HttpRequestMessage requestMessage)
        {
            if (exception is UnhandledGraphiteException)
            {
                return(exception.As <UnhandledGraphiteException>()
                       .GetDebugResponse(requestMessage));
            }

            var message = new StringBuilder(10.KB());

            message
            .AppendLine("Action".WriteHeader())
            .AppendLine()
            .AppendLine($"Url Template: {requestMessage.RequestUri}")
            .AppendLine()
            .AppendLine("Request".WriteHeader())
            .AppendLine()
            .AppendLine($"{requestMessage.RequestUri}")
            .AppendLine()
            .AppendLine(requestMessage.RawHeaders())
            .AppendLine()
            .AppendLine("Exception".WriteHeader())
            .AppendLine()
            .AppendLine(exception.ToFriendlyException());

            return(message.ToString());
        }
        public static string ToDisplayMessage(Exception ex, out ErrorDisplay errorDisplay)
        {
            if (ex is StorytellerFailureException)
            {
                var failure = ex.As <StorytellerFailureException>();

                errorDisplay = failure.ErrorDisplay;
                return(failure.FormattedMessage());
            }

            var exType = ex.GetType();

            if (_textualErrors.Has(exType))
            {
                errorDisplay = ErrorDisplay.text;
                return(_textualErrors[exType](ex));
            }

            if (_markdownErrors.Has(exType))
            {
                errorDisplay = ErrorDisplay.markdown;
                return(_markdownErrors[exType](ex));
            }


            errorDisplay = ErrorDisplay.text;
            return(ex.ToString());
        }
 public CommandResponse(Exception e)
 {
     if (e == null)
     {
         return;
     }
     Error     = e.Message;
     ErrorNote = e.As <string>();
 }
        /// <summary>检查应答原因</summary>
        private void CheckResponseReason(Exception ex)
        {
            var rex = ex.As <HttpResponseException>();

            if (rex != null)
            {
                rex.SetResponseReason(rex.Response);
                return;
            }
        }
        public void Should_throw_validation_exception_if_Request_is_null(
            IRequestHandler <Request, Response> validationHandler,
            Exception exception
            )
        {
            "Given a ValidationHandler"
            .Given(() => validationHandler = new ValidationHandler <Request, Response>(new Container(), new RequestHandler()));

            "When handling a null Request"
            .When(() => exception = Record.Exception(() => validationHandler.Handle(null)));

            "Then a ValidationException should be thrown"
            .Then(() => exception.Should().BeOfType <ValidationException>());

            "And the error property should be 'Request'"
            .Then(() => exception.As <ValidationException>().Errors.Single().PropertyName.Should().Be("Request"));

            "And the error message should be 'Request cannot be null'"
            .Then(() => exception.As <ValidationException>().Errors.Single().ErrorMessage.Should().Be("Request cannot be null"));
        }
        public void Should_throw_when_Container_is_null(
            Exception exception)
        {
            "When constructing a SimpleInjectorDependencyResolver with a null Container"
            .When(() => exception = Record.Exception(() => new SimpleInjectorDependencyResolver(null)));

            "Then an ArgumentNullException should be thrown"
            .Then(() => exception.Should().BeOfType <ArgumentNullException>());

            "An the parameter name should be 'container'"
            .Then(() => exception.As <ArgumentNullException>().ParamName.Should().Be("container"));
        }
Esempio n. 9
0
        public static void ConfiguringSetterWithNull(
            Exception exception)
        {
            "When assignment of a property is configured using a null expression"
            .x(() => exception = Record.Exception(() => A.CallToSet <int>(null)));

            "Then an argument null exception is thrown"
            .x(() => exception.Should().BeAnExceptionOfType <ArgumentNullException>());

            "And the parameter name is 'propertySpecification'"
            .x(() => exception.As <ArgumentNullException>().ParamName.Should().Be("propertySpecification"));
        }
Esempio n. 10
0
        public void Should_throw_when_genres_null(
            Exception exception)
        {
            "When constructing a Movie with a null genres collection"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithGenres(null).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'genres'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("genres"));
        }
Esempio n. 11
0
 public static T ReturnInvalidResult <T>(Exception e)
 {
     if (e is CommunicationObjectAbortedException)
     {
         return(default(T));
     }
     if (e is CommunicationException)
     {
         return(default(T));
     }
     System.Diagnostics.Trace.WriteLine(e.As <string>());
     return(Je.meta.IsTypeOf(typeof(T), typeof(Exception)) ? (T)(object)e : default(T));
 }
Esempio n. 12
0
        public void Should_throw_when_title_is_null_empty_or_greater_than_128_characters(
            string title,
            Exception exception)
        {
            "When constructing a Movie with title '{0}'"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithTitle(title).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'title'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("title"));
        }
Esempio n. 13
0
 public void ReadException(Exception exception)
 {
     if (exception is AggregateException)
     {
         ExceptionText = exception.As <AggregateException>()
                         .InnerExceptions.Select(x => x.ToString())
                         .Join(ExceptionSeparator);
     }
     else
     {
         ExceptionText = exception.ToString();
     }
 }
Esempio n. 14
0
        public void Should_throw_when_rating_is_negative_or_greather_than_10(
            decimal rating,
            Exception exception)
        {
            "When constructing a Movie with rating '{0}'"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithRating(rating).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'rating'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("rating"));
        }
Esempio n. 15
0
        public void Should_throw_when_plot_is_null_empty_or_greater_than_256_characters(
            string plot,
            Exception exception)
        {
            "When constructing a Movie with plot '{0}'"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithPlot(plot).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'plot'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("plot"));
        }
Esempio n. 16
0
        public void Should_throw_when_director_is_null_empty_or_greater_than_64_characters(
            string director,
            Exception exception)
        {
            "When constructing a Movie with director '{0}'"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithDirector(director).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'director'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("director"));
        }
Esempio n. 17
0
        public void Should_throw_when_imdb_id_is_null_or_not_exactly_9_characters(
            string imdbId,
            Exception exception)
        {
            "When constructing a Movie with imdbId '{0}'"
            .When(() => exception = Record.Exception(() => new MovieBuilder().WithImdbId(imdbId).Build()));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'imdbId'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("imdbId"));
        }
Esempio n. 18
0
        public void Should_throw_when_name_is_null_empty_or_greater_than_64_characters(
            string name,
            Exception exception)
        {
            "When constructing a Movie with name '{0}'"
            .When(() => exception = Record.Exception(() => new Genre(name)));

            "Then an ArgumentException should be thrown"
            .Then(() => exception.Should().BeAssignableTo <ArgumentException>());

            "With a parameter name of 'name'"
            .And(() => exception.As <ArgumentException>().ParamName.Should().Be("name"));
        }
Esempio n. 19
0
        /// <summary>获得完整异常信息</summary>
        public static string GetFullMessage(this Exception ex, int level = 0)
        {
            var sBuilder = new StringBuilder();

            sBuilder.Append(ex.Message);
            var ufex = ex.As <UserFriendlyException>();

            if (ufex != null)
            {
                sBuilder.Append(ufex.FriendlyMessage);
            }
            var indent = (level + 1) * 2;
            var aex    = ex.As <AggregateException>();

            if (aex != null)
            {
                sBuilder.AppendLine();
                for (int i = 0; i < indent; i++)
                {
                    sBuilder.Append(' ');
                }
                foreach (var innerException in aex.InnerExceptions)
                {
                    sBuilder.Append(GetFullMessage(innerException, level + 1));
                }
            }
            else if (ex.InnerException != null)
            {
                sBuilder.AppendLine();
                for (int i = 0; i < indent; i++)
                {
                    sBuilder.Append(' ');
                }
                sBuilder.Append(GetFullMessage(ex.InnerException, level + 1));
            }
            return(sBuilder.ToString());
        }
        private static Exception GetInnerException(AggregateException aggregateException)
        {
            Exception innerExcception = aggregateException;

            while (aggregateException is AggregateException)
            {
                innerExcception    = aggregateException.InnerExceptions[0];
                aggregateException = innerExcception.As <AggregateException>();
                if (aggregateException.IsNull())
                {
                    break;
                }
            }
            return(innerExcception);
        }
Esempio n. 21
0
        public void CanWriteType_throws_if_type_is_null(
            ServiceStackJsonFormatter formatter,
            Exception exception)
        {
            "Given a ServiceStackJsonFormatter"
            .Given(() => formatter = new ServiceStackJsonFormatter());

            "When calling CanWriteType with a null type"
            .When(() => exception = Record.Exception(() => formatter.CanWriteType(null)));

            "Then an ArgumentNullException should be thrown"
            .Then(() => exception.Should().BeOfType <ArgumentNullException>());

            "With a parameter name of 'type'"
            .Then(() => exception.As <ArgumentNullException>().ParamName.Should().Be("type"));
        }
Esempio n. 22
0
        /// <summary>转换为异常数据</summary>
        public static ExceptionModel ToModel(this Exception ex)
        {
            var model = new ExceptionModel();
            var ex2   = ex.As <UserFriendlyException>();

            if (ex2 == null)
            {
                model.Code    = ex.Data[Code].As <string>();
                model.Message = ex.Data[Details].As <string>();
            }
            else
            {
                model.Code    = ex2.Code;
                model.Message = ex2.FriendlyMessage;
            }
            model.Details = ex.GetFullMessage();
            return(model);
        }
Esempio n. 23
0
    private async Task HandleAndWrapException(HttpContext httpContext, Exception exception)
    {
        _logger.LogException(exception);

        await httpContext
        .RequestServices
        .GetRequiredService <IExceptionNotifier>()
        .NotifyAsync(
            new ExceptionNotificationContext(exception)
            );

        if (exception is AbpAuthorizationException)
        {
            await httpContext.RequestServices.GetRequiredService <IAbpAuthorizationExceptionHandler>()
            .HandleAsync(exception.As <AbpAuthorizationException>(), httpContext);
        }
        else
        {
            var errorInfoConverter       = httpContext.RequestServices.GetRequiredService <IExceptionToErrorInfoConverter>();
            var statusCodeFinder         = httpContext.RequestServices.GetRequiredService <IHttpExceptionStatusCodeFinder>();
            var jsonSerializer           = httpContext.RequestServices.GetRequiredService <IJsonSerializer>();
            var exceptionHandlingOptions = httpContext.RequestServices.GetRequiredService <IOptions <AbpExceptionHandlingOptions> >().Value;

            httpContext.Response.Clear();
            httpContext.Response.StatusCode = (int)statusCodeFinder.GetStatusCode(httpContext, exception);
            httpContext.Response.OnStarting(_clearCacheHeadersDelegate, httpContext.Response);
            httpContext.Response.Headers.Add(AbpHttpConsts.AbpErrorFormat, "true");
            httpContext.Response.Headers.Add("Content-Type", "application/json");

            await httpContext.Response.WriteAsync(
                jsonSerializer.Serialize(
                    new RemoteServiceErrorResponse(
                        errorInfoConverter.Convert(exception, options =>
            {
                options.SendExceptionsDetailsToClients = exceptionHandlingOptions.SendExceptionsDetailsToClients;
                options.SendStackTraceToClients        = exceptionHandlingOptions.SendStackTraceToClients;
            })
                        )
                    )
                );
        }
    }
 private void Write(Exception e, string methodName)
 {
     try
     {
         if (WriteTyped(e))
         {
             return;
         }
         System.Diagnostics.Trace.WriteLine($"{methodName}:{Environment.NewLine}{e.Message}{Environment.NewLine}{e.As<string>()}{Environment.NewLine}");
     }
     catch
     {
         System.Threading.Thread.Sleep(111);
     }
 }
Esempio n. 25
0
        public void ThenExceptionIsThrown()
        {
            _caughtException.Should().BeOfType <HttpRequestException>();

            _caughtException.As <HttpRequestException>().Message.Should().StartWith("Response status code does not indicate success: 429");
        }
Esempio n. 26
0
 public bool Matches(Envelope envelope, Exception ex)
 {
     return(ex is T && _filter(ex.As <T>()));
 }