Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion samples/MiddlewareSample/MiddlewareSample.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@

// Register custom exceptions and status codes
builder.Services
// .AddExceptionsMiddleware() -> Use this extension for default correlation key/value
// .AddExceptionsMiddleware() -> Use this extension for default correlation key/value and configuration
.AddExceptionsMiddleware(options =>
{
options.CorrelationKey = "X-TestCorrelation-Id";
options.CorrelationKey = CORRELATION_HEADER_KEY;
options.ConfigureCorrelationValue = (httpContext) => httpContext.TraceIdentifier;

options.ConfigureProblemDetails = (httpContext, exception, problemDetails) =>
{
Console.WriteLine("Here you can override the ProblemDetails object returned to the client.");
Console.WriteLine("Also a good place to breakpoint during development to examine thrown exceptions.");
return problemDetails;
};
}) // Use this extension for default correlation key/value
.AddException<RandomException>(HttpStatusCode.FailedDependency);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,11 @@ async Task LogAndWriteProblemDetailsExceptionAsync(ProblemDetails problemDetails

httpContext.Response.StatusCode = problemDetails.Status ?? (int)HttpStatusCode.InternalServerError;

if (exceptionsMiddlewareOptionsValue.ConfigureProblemDetails is not null)
{
problemDetails = exceptionsMiddlewareOptionsValue.ConfigureProblemDetails(httpContext, exception, problemDetails);
}

await httpContext.Response.WriteAsJsonAsync(
problemDetails,
problemDetails.GetType(), // WriteAsJson needs type to add additional fields provided in ValidationProblemDetails
Expand Down
6 changes: 6 additions & 0 deletions src/Middleware/src/ExceptionsMiddlewareOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// -------------------------------------------------------

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace BlazorFocused.Exceptions.Middleware;
Expand Down Expand Up @@ -32,4 +33,9 @@ public class ExceptionsMiddlewareOptions
/// Default error status code if none specified for given type of exception
/// </summary>
public HttpStatusCode DefaultErrorStatusCode { get; set; } = HttpStatusCode.InternalServerError;

/// <summary>
/// Provide a way to override/configure the ProblemDetails object before it is returned to the client
/// </summary>
public Func<HttpContext, Exception, ProblemDetails, ProblemDetails> ConfigureProblemDetails { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Licensed under the MIT License
// -------------------------------------------------------

using BlazorFocused.Exceptions.Middleware.ApplicationBuilder;
using BlazorFocused.Exceptions.Middleware.ExceptionBuilder;
using Bogus;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
Expand All @@ -11,8 +13,6 @@
using Microsoft.Extensions.Options;
using Moq;
using System.Net;
using BlazorFocused.Exceptions.Middleware.ApplicationBuilder;
using BlazorFocused.Exceptions.Middleware.ExceptionBuilder;

namespace BlazorFocused.Exceptions.Middleware.Test.ApplicationBuilder;

Expand All @@ -30,7 +30,7 @@ public async Task Invoke_ShouldReturnProblemDetailsNoConfiguration(Exception thr

requestDelegateMock.Setup(request =>
request.Invoke(httpContext))
.ThrowsAsync(thrownException);
.ThrowsAsync(thrownException);

Exception actualException =
await Record.ExceptionAsync(() =>
Expand All @@ -54,7 +54,8 @@ await Record.ExceptionAsync(() =>

[Theory]
[MemberData(nameof(ExceptionsWithStatusCode))]
public async Task Invoke_ShouldReturnProblemDetailsWithDefaultMessage(Exception thrownException, HttpStatusCode expectedStatusCode)
public async Task Invoke_ShouldReturnProblemDetailsWithDefaultMessage(Exception thrownException,
HttpStatusCode expectedStatusCode)
{
using MemoryStream memoryStream =
GenerateHttpContext(out string expectedInstance, out HttpContext httpContext);
Expand All @@ -73,7 +74,7 @@ public async Task Invoke_ShouldReturnProblemDetailsWithDefaultMessage(Exception

requestDelegateMock.Setup(request =>
request.Invoke(httpContext))
.ThrowsAsync(thrownException);
.ThrowsAsync(thrownException);

Exception actualException =
await Record.ExceptionAsync(() =>
Expand Down Expand Up @@ -125,7 +126,7 @@ public async Task Invoke_ShouldReturnProblemDetailsWithConfiguredMessage()

requestDelegateMock.Setup(request =>
request.Invoke(httpContext))
.ThrowsAsync(thrownException);
.ThrowsAsync(thrownException);

Exception actualException =
await Record.ExceptionAsync(() =>
Expand All @@ -147,4 +148,58 @@ await Record.ExceptionAsync(() =>
Assert.Equal((int)expectedStatusCode, httpContext.Response.StatusCode);
Assert.Equal(thrownException.GetType().Name, actualErrorResponse.Type);
}

[Fact]
public async Task Invoke_ShouldAllowProblemDetailsOverride()
{
string exceptionMessage = new Faker().Lorem.Sentence();
string expectedType = "Test Override 1";
string overrideInstance = " - Test Override 2";
string overrideMessage = "Test Override 3 ";
string expectedDetail = overrideMessage + exceptionMessage;
int expectedStatusCode = (int)HttpStatusCode.GatewayTimeout;
var thrownException = new ApplicationException(exceptionMessage);

using MemoryStream memoryStream =
GenerateHttpContext(out string initialInstance, out HttpContext httpContext);

string expectedInstance = initialInstance + overrideInstance;

IOptionsMonitor<ExceptionsMiddlewareBuilderOptions> optionsMonitor = null;
var exceptionsMiddlewareOptions = new ExceptionsMiddlewareOptions
{
ConfigureProblemDetails = (httpContext, exceptionMessage, problemDetails) =>
{
problemDetails.Detail = overrideMessage + exceptionMessage.Message;
problemDetails.Instance = httpContext.Request.Path + httpContext.Request.QueryString + overrideInstance;
problemDetails.Status = expectedStatusCode;
problemDetails.Type = expectedType;

return problemDetails;
}
};

requestDelegateMock.Setup(request =>
request.Invoke(httpContext))
.ThrowsAsync(thrownException);

Exception actualException =
await Record.ExceptionAsync(() =>
applicationBuilderMiddleware.Invoke(
httpContext,
Options.Create(exceptionsMiddlewareOptions),
optionsMonitor,
NullLogger<ApplicationBuilderMiddleware>.Instance));

ProblemDetails actualErrorResponse = await GetErrorResponseFromBody<ProblemDetails>(memoryStream);

// Should be null since error is caught
actualException.Should().BeNull();

Assert.Equal(expectedDetail, actualErrorResponse.Detail);
Assert.Equal(expectedInstance, actualErrorResponse.Instance);
Assert.Equal(expectedStatusCode, actualErrorResponse.Status);
Assert.Equal(expectedType, actualErrorResponse.Type);
Assert.NotEqual(expectedStatusCode, httpContext.Response.StatusCode);
}
}