Skip to content

Instantly share code, notes, and snippets.

@DocGreenRob
Created September 24, 2021 18:27
Show Gist options
  • Save DocGreenRob/99ec90d27579ded031bad3cdcb153540 to your computer and use it in GitHub Desktop.
Save DocGreenRob/99ec90d27579ded031bad3cdcb153540 to your computer and use it in GitHub Desktop.
ExceptionMiddleware Example
using Cge.Core.Extensions;
using Cge.Core.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Threading.Tasks;
namespace HomeaZZon.Api.Middlewares
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ITelemetryClient _telemetryClient;
public ExceptionMiddleware(RequestDelegate next, ITelemetryClient telemetryClient)
{
_next = next;
_telemetryClient = telemetryClient.ValidateArgNotNull(nameof(telemetryClient));
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
string result = JsonConvert.SerializeObject(new { Message = $"{ex.Message} {(ex.InnerException != null ? ex.InnerException.Message : "")}" });
if (ex is ValidationException)
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
_telemetryClient.TrackException(ex);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(result);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment