Skip to content

3. Rethrow exceptions instead of http response

Michal Motyčka edited this page Jul 9, 2023 · 1 revision

Let's say we have the following controller:

[GenerateClient]
public class ExamplesController : ControllerBase
{
    [HttpGet("ActionWithError")]
    public ActionResult ActionWithError()
    {
        throw new InvalidOperationException("Something went wrong unexpectedly.");
    }
}

And a test that calls this controller:

[Test]
public async Task ThrowExceptionTest()
{
    using var webApplicationFactory = new WebApplicationFactory<Program>().WithRidge();
    var httpClient = webApplicationFactory.CreateClient();
    var examplesControllerClient = new ExamplesControllerClient(httpClient, webApplicationFactory.Services);
    
    var response = await examplesControllerClient.ActionWithError();
    
    Assert.True(response.IsSuccessStatusCode);
}

This test will fail with the error 'Expected: True But Was: False' no further information is provided. This is less than ideal, because we don't know what went wrong.

To improve the debugging experience, Ridge offers special middleware that can be added to your ASP.NET pipeline. This middleware saves the exception and then rethrows it in test code. To add this middleware, use the following example:

// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// WasApplicationCreatedFromTest and RethrowExceptionInsteadOfReturningHttpResponse are extension methods from Ridge package
if (app.WasApplicationCreatedFromTest())
{
    app.RethrowExceptionInsteadOfReturningHttpResponse();
}
app.UseStaticFiles();
app.Run();

With this middleware previous test throws exception "System.InvalidOperationException: Something went wrong unexpectedly.".

Filter exceptions

In some cases it is necessary not to throw exception and return response instead. In those cases it is possible to use ExceptionRethrowFilter:

WebApplicationFactory = webApplicationFactory.WithRidge(x =>
{
    x.UseExceptionRethrowFilter((e) => e is ExceptionNotToBeRethrown ? false : true);
});

This example causes all exceptions except ExceptionNotToBeRethrown to be thrown as exception. Exceptions of type ExceptionNotToBeRethrown will be processed as usual and returned as http response.