8

I have created a custom middleware to handle exceptions in my Api app.

I want to correlate a request id with the exception and any other logging I do in the app. I then want to handle any exceptions and respond to the client with the requestId I generated.

This would allow them to contact me with a requestId which I could look up in my logs and see what was going on when they received their error.

Here is the Invoke of my middleware and the sending of the requestId in the response.

public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
{
    var requestId = Guid.NewGuid();
    var requestScopeLogger = loggerFactory.CreateLogger("AppRequest");

    using (requestScopeLogger.BeginScope("Request {requestId}", requestId))
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex, requestId);
        }
    }
}

private Task HandleExceptionAsync(HttpContext context, Exception exception, Guid requestId)
{
    ...
    var response = JsonConvert.SerializeObject(new { errorMessage = clientResult.message, requestId });

    context.Response.ContentType = "application/json";
    context.Response.StatusCode = (int)clientResult.code;

    return context.Response.WriteAsync(response);
}

The middleware is registered before anything else (StaticFiles, Swagger, Mvc) in my Startup.Configure

Everything seems to be working correctly when I test throwing exceptions in my Api business logic or controllers.

Is this an acceptable use of ILogger.BeginScope? Is it ok to wrap the middleware pipeline in this way despite it being async?

seangwright
  • 17,245
  • 6
  • 42
  • 54

0 Answers0