public async void MiddlewareShouldCatchNonBusinessExceptionsWithInternalServerErrorAndNoResponse()
        {
            var message = Guid.NewGuid().ToString();

            RequestDelegate requestDelegate =
                (innerHttpContext) => throw new InvalidOperationException(message);
            var middleware = new ExceptionHandlingMiddleware(requestDelegate, _loggerMock.Object);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(context.Response.Body))
            {
                var streamText = reader.ReadToEnd();
                Assert.Empty(streamText);
            }

            Assert.Equal((int)HttpStatusCode.InternalServerError, context.Response.StatusCode);
            _loggerMock.Verify(
                x => x.Log <object>(
                    LogLevel.Error,
                    It.IsAny <EventId>(),
                    It.Is <object>(y => y.ToString() == message),
                    It.IsAny <Exception>(),
                    It.IsAny <Func <object, Exception, string> >()),
                Times.Once());
        }
Ejemplo n.º 2
0
        public async Task Write_400_Response_If_ValidationException_Is_Thrown()
        {
            var failures = new List <ValidationFailure>
            {
                new ValidationFailure("name", "name can not be empty")
            };

            var exception = new ValidationException(failures);

            Task next(HttpContext context)
            {
                throw exception;
            }

            var middleware = new ExceptionHandlingMiddleware(next);
            var context    = HttpContextFactory.Create();

            await middleware.Invoke(context);

            Assert.AreEqual("application/json", context.Response.ContentType);
            Assert.AreEqual(400, context.Response.StatusCode);

            var failuresResponse = await context.Response.ReadAsAsync <List <ValidationFailure> >();

            Assert.AreEqual(exception.Errors.ToList()[0].ErrorMessage, failuresResponse[0].ErrorMessage);
        }
Ejemplo n.º 3
0
        public IPipelineBuilder UseExceptionHandler(Func <HttpContext, Task <IActionResult> > executeFunctions)
        {
            PipelineBuilder builder = new PipelineBuilder(this._httpContextAccessor);

            var middleware = new ExceptionHandlingMiddleware();

            return(builder.Use(middleware)
                   .Use(new FunctionsMiddleware(executeFunctions)));
        }
Ejemplo n.º 4
0
        public async Task WhenExecutingExceptionMiddleware_GivenAnHttpContextWithNoException_TheResponseShouldBeEmpty()
        {
            ExceptionHandlingMiddleware baseExceptionMiddleware = CreateExceptionHandlingMiddleware(innerHttpContext => Task.CompletedTask);

            await baseExceptionMiddleware.Invoke(_context);

            Assert.Equal(200, _context.Response.StatusCode);
            Assert.Null(_context.Response.ContentType);
            Assert.Equal(0, _context.Response.Body.Length);
        }
        public ExceptionHandlingMiddlewareTests()
        {
            _innerFunction = Substitute.For <IDummyRequestDelegate>();
            _next          = async(context) =>
            {
                await _innerFunction.CallMe(context);

                await Task.CompletedTask;
            };

            _middleware = Substitute.ForPartsOf <ExceptionHandlingMiddleware>(_next);
        }
        private async Task <string> AssertTest(DefaultHttpContext context, ExceptionHandlingMiddleware middleware)
        {
            context.Response.Body = new MemoryStream();

            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader     = new StreamReader(context.Response.Body);
            var streamText = reader.ReadToEnd();

            return(streamText);
        }
Ejemplo n.º 7
0
        public async void Should_logSuccessMessage()
        {
            //Arrange
            var mockedLogger          = Mock.Of <ILogger <ExceptionHandlingMiddleware> >();
            var correlationMiddleWare = new ExceptionHandlingMiddleware(mockedLogger);
            var sentMessage           = new { Field = "value" };
            var envelope = new MessagingEnvelope(new System.Collections.Generic.Dictionary <string, string>(), sentMessage);

            Task next() => Task.CompletedTask;

            //Act
            await correlationMiddleWare.Invoke(new MessagingContext(envelope, string.Empty, null), default, next);
Ejemplo n.º 8
0
        public async Task GivenAnException_WhenMiddlewareIsExecuted_ThenCorrectStatusCodeShouldBeRetruned(Exception exception, HttpStatusCode expectedStatusCode)
        {
            ExceptionHandlingMiddleware baseExceptionMiddleware = CreateExceptionHandlingMiddleware(innerHttpContext => throw exception);

            baseExceptionMiddleware.ExecuteResultAsync(Arg.Any <HttpContext>(), Arg.Any <IActionResult>()).Returns(Task.CompletedTask);

            await baseExceptionMiddleware.Invoke(_context);

            await baseExceptionMiddleware
            .Received()
            .ExecuteResultAsync(
                Arg.Any <HttpContext>(),
                Arg.Is <ContentResult>(x => x.StatusCode == (int)expectedStatusCode));
        }
        public async Task WhenANormalRequestIsMade()
        {
            // Arrange
            RequestDelegate next       = (HttpContext hc) => Task.CompletedTask;
            var             middleware = new ExceptionHandlingMiddleware(next);

            var context = new DefaultHttpContext();

            await AssertTest(context, middleware);

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.OK);
        }
Ejemplo n.º 10
0
        public async Task GivenAnInternalServerException_WhenMiddlewareIsExecuted_ThenMessageShouldBeOverwritten()
        {
            ExceptionHandlingMiddleware baseExceptionMiddleware = CreateExceptionHandlingMiddleware(innerHttpContext => throw new Exception("Unhandled exception."));

            baseExceptionMiddleware.ExecuteResultAsync(Arg.Any <HttpContext>(), Arg.Any <IActionResult>()).Returns(Task.CompletedTask);

            await baseExceptionMiddleware.Invoke(_context);

            await baseExceptionMiddleware
            .Received()
            .ExecuteResultAsync(
                Arg.Any <HttpContext>(),
                Arg.Is <ContentResult>(x => x.Content == DicomApiResource.InternalServerError));
        }
Ejemplo n.º 11
0
        public async Task Call_Next_If_No_Exception()
        {
            var isCalled = false;

            Task next(HttpContext context)
            {
                isCalled = true;
                return(Task.FromResult(0));
            }

            var middleware = new ExceptionHandlingMiddleware(next);

            await middleware.Invoke(null);

            Assert.IsTrue(isCalled);
        }
        public async Task WhenANotFoundExceptionIsRaised()
        {
            var middleware = new ExceptionHandlingMiddleware((innerHttpContext) =>
            {
                throw new NotFoundException("Not found");
            });

            var context    = new DefaultHttpContext();
            var streamText = await AssertTest(context, middleware);

            streamText.Should().BeEquivalentTo("Not found");

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.NotFound);
        }
            public async Task It_returns_500_when_unhandled_exception_is_thrown()
            {
                const int expected = StatusCodes.Status500InternalServerError;

                var e = new FormatException();

                var next = ThrowableRequestDelegate(e);

                var sut = new ExceptionHandlingMiddleware(next);

                await sut.Invoke(_httpContext);

                var actual = _httpContext.Response.StatusCode;

                Assert.Equal(expected, actual);
            }
            public async Task It_returns_404_when_rss_not_parsable_is_thrown()
            {
                const int expected = StatusCodes.Status404NotFound;

                var e = new RssNotParsableException();

                var next = ThrowableRequestDelegate(e);

                var sut = new ExceptionHandlingMiddleware(next);

                await sut.Invoke(_httpContext);

                var actual = _httpContext.Response.StatusCode;

                Assert.Equal(expected, actual);
            }
        public async Task WhenAnUnExpectedExceptionIsRaised()
        {
            var middleware = new ExceptionHandlingMiddleware(next: (innerHttpContext) =>
            {
                throw new Exception("Test");
            });

            var context    = new DefaultHttpContext();
            var streamText = await AssertTest(context, middleware);

            streamText.Should().BeEquivalentTo("Bad Request");

            context.Response.StatusCode
            .Should()
            .Be((int)HttpStatusCode.BadRequest);
        }
        public async Task ExecuteAsync_CommonException_HandlesException()
        {
            var exceptionHandler = new SyncPingCommonExceptionHandler();

            var middleware = new ExceptionHandlingMiddleware <Ping, int>(new[] { exceptionHandler });

            var query   = new Ping();
            var handler = new BrokenPingHandler();

            var actual = await middleware.ExecuteAsync(
                query,
                () => handler.HandleAsync(query, default),
                default
                );

            actual.Should().Be(exceptionHandler.Value);
        }
Ejemplo n.º 17
0
        public async Task Write_404_Response_If_NotFound_Is_Thrown()
        {
            var exception = new NotFoundException("Category", 1);

            Task next(HttpContext context)
            {
                throw exception;
            }

            var middleware = new ExceptionHandlingMiddleware(next);
            var context    = HttpContextFactory.Create();

            await middleware.Invoke(context);

            Assert.AreEqual("application/json", context.Response.ContentType);
            Assert.AreEqual(404, context.Response.StatusCode);
            Assert.AreEqual(exception.Message, await context.Response.ReadAsAsync <string>());
        }
Ejemplo n.º 18
0
        public async Task Write_500_Response_If_Anonther_Is_Thrown()
        {
            var exception = new Exception("input invalid");

            Task next(HttpContext context)
            {
                throw exception;
            }

            var middleware = new ExceptionHandlingMiddleware(next);
            var context    = HttpContextFactory.Create();

            await middleware.Invoke(context);

            Assert.AreEqual("application/json", context.Response.ContentType);
            Assert.AreEqual(500, context.Response.StatusCode);
            Assert.AreEqual(exception.Message, await context.Response.ReadAsAsync <string>());
        }
        public async Task ExecuteAsync_MultipleExceptionHandlers_UsesConcreteHandler()
        {
            var concreteExceptionHandler = new SyncPingConcreteExceptionHandler();

            var middleware = new ExceptionHandlingMiddleware <Ping, int>(
                new IQueryExceptionHandler <Ping, int>[]
            {
                new SyncPingCommonExceptionHandler(),
                concreteExceptionHandler
            }
                );

            var query   = new Ping();
            var handler = new BrokenPingHandler();

            var actual = await middleware.ExecuteAsync(
                query,
                () => handler.HandleAsync(query, default),
                default
                );

            actual.Should().Be(concreteExceptionHandler.Value);
        }
        public async void MiddlewareShouldCatchBusinessExceptionsWithBadRequestAndMessageTest()
        {
            var message = Guid.NewGuid().ToString();

            RequestDelegate requestDelegate = (innerHttpContext) => throw new BusinessException(message);
            var             middleware      = new ExceptionHandlingMiddleware(requestDelegate, _loggerMock.Object);

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(context.Response.Body, Encoding.UTF8))
            {
                var streamText = reader.ReadToEnd();
                Assert.Equal(message, streamText);
            }

            Assert.Equal((int)HttpStatusCode.BadRequest, context.Response.StatusCode);
        }
 public ExceptionHandlingMiddlewareTest()
 {
     _httpContext.Response.Body = _responseStream;
     _sut = new ExceptionHandlingMiddleware(_next);
 }