Skip to content

Instantly share code, notes, and snippets.

@ankitvijay
Created April 18, 2021 20:28
Show Gist options
  • Select an option

  • Save ankitvijay/4fc273d5219ec2cd73e733ebdc2fd6ff to your computer and use it in GitHub Desktop.

Select an option

Save ankitvijay/4fc273d5219ec2cd73e733ebdc2fd6ff to your computer and use it in GitHub Desktop.
Consistent Error Logging - Application Exception Middleware
using System;
using System.Net.Mime;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
public class ApplicationExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly IExceptionHandler _exceptionHandler;
private readonly ILogger<ApplicationExceptionMiddleware> _logger;
public ApplicationExceptionMiddleware(
RequestDelegate next,
IExceptionHandler exceptionHandler,
ILogger<ApplicationExceptionMiddleware> logger)
{
_next = next;
_exceptionHandler = exceptionHandler;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
var errorDocument = _exceptionHandler.HandleException(ex);
if (!httpContext.Response.HasStarted)
{
httpContext.Response.Clear();
httpContext.Response.ContentType = MediaTypeNames.Application.Json;
httpContext.Response.StatusCode = (int) errorDocument.StatusCode;
await httpContext.Response.WriteAsync(JsonSerializer.Serialize(
errorDocument));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment