public async void HandleException_Should_Set_Response_Body_With_DetailedResponse() { var exception = new Exception("ExceptionMessage"); var context = new DefaultHttpContext(); context.Response.Body = new MemoryStream(); await _middleware.HandleException(exception, context); JToken body; context.Response.Body.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(context.Response.Body)) { var content = await reader.ReadToEndAsync(); body = JToken.Parse(content); } var expected = ApiResponseHelper.Error("An unhandled exception has occurred.", exception.Message); var result = (ObjectResult)expected.Result; var expectedBody = JToken.FromObject(result.Value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); body.Should().BeEquivalentTo(expectedBody); }
public virtual async Task HandleException(Exception ex, HttpContext context) { var message = "An unhandled exception has occurred."; var response = ApiResponseHelper.Error(message, ex.Message); var result = (ObjectResult)response.Result; context.Response.StatusCode = result.StatusCode ?? StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(result.Value, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })); }
public void Error_Should_Return_Correctly() { var message = "message"; var actual = ApiResponseHelper.Error(message); actual.Should().BeOfType <ActionResult <ApiResponse> >(); actual.Result.Should().BeOfType <ObjectResult>(); actual.Result.As <ObjectResult>().StatusCode.Should().Be(StatusCodes.Status500InternalServerError); actual.Result.As <ObjectResult>().Value.Should().BeOfType <ApiResponse>(); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Success.Should().Be(false); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Message.Should().Be(message); actual.Result.As <ObjectResult>().Value.As <ApiResponse>().Data.Should().BeNull(); }