public async Task WhenAnUnExpectedExceptionIsRaised_CustomExceptionMiddlewareShouldHandleItToCustomErrorResponseAndInternalServerErrorHttpStatus()
        {
            // Arrange
            var middleware = new ExceptionHandlingMiddleware((innerHttpContext) => throw new Exception("Test"));

            var context = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            // Act
            await middleware.Invoke(context).ConfigureAwait(false);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var reader               = new StreamReader(context.Response.Body);
            var streamText           = reader.ReadToEnd();
            var objResponse          = JsonConvert.DeserializeObject <CustomErrorResponse>(streamText);
            var expectedStatusCode   = context.Response.StatusCode;
            var expectedResponseBody = new CustomErrorResponse {
                Message = "Unexpected error", Description = "Unexpected error"
            };

            // Assert
            Assert.Equal(expectedResponseBody, objResponse);
            Assert.Equal(expectedStatusCode, (int)HttpStatusCode.InternalServerError);
        }
        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var response        = context.Response;
            var customException = exception as BaseException;
            var statusCode      = (int)HttpStatusCode.InternalServerError;
            CustomErrorResponse customErrorResponse = new CustomErrorResponse()
            {
                Code    = statusCode,
                Message = "Unexpected Error Occured"
            };

            if (customException != null)
            {
                customErrorResponse.Code    = customException.Code;
                customErrorResponse.Message = customException.Message;
                customErrorResponse.Info    = customException.Info;
                statusCode = (int)customException.HttpStatusCode;
            }

            response.ContentType = "application/json";
            response.StatusCode  = statusCode;

            return(response.WriteAsync(JsonConvert.SerializeObject(customErrorResponse, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            })));
        }
Пример #3
0
            static IActionResult handler(HttpContext context, ModelValidationResult validationResult)
            {
                CustomErrorResponse response = new CustomErrorResponse()
                {
                    CustomErrorMessage = "Custom error: The Id field is required",
                };

                return(new ObjectResult(response)
                {
                    StatusCode = 409,
                });
            }