Skip to content

Instantly share code, notes, and snippets.

@Kurtz1993
Last active April 1, 2021 00:10
Show Gist options
  • Save Kurtz1993/6361a7b8d2da9753acf8cad3e780a491 to your computer and use it in GitHub Desktop.
Save Kurtz1993/6361a7b8d2da9753acf8cad3e780a491 to your computer and use it in GitHub Desktop.
using System;
using System.Net;
using System.Reflection;
using System.Security.Authentication;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace App.Middleware
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (ArgumentException ex)
{
await SendResponseAsync(HttpStatusCode.BadRequest, ex.Message, httpContext);
}
catch (InvalidCredentialException ex)
{
await SendResponseAsync(HttpStatusCode.Unauthorized, ex.Message, httpContext);
}
catch (InvalidOperationException ex)
{
await SendResponseAsync(HttpStatusCode.Forbidden, ex.Message, httpContext);
}
catch (NullReferenceException ex)
{
await SendResponseAsync(HttpStatusCode.NotFound, ex.Message, httpContext);
}
catch (AmbiguousMatchException ex)
{
await SendResponseAsync(HttpStatusCode.Conflict, ex.Message, httpContext);
}
catch (Exception ex)
{
await SendResponseAsync(HttpStatusCode.InternalServerError, ex.Message, httpContext);
}
}
private async Task SendResponseAsync(HttpStatusCode statusCode, string message, HttpContext httpContext)
{
var response = new ApiMessageResponse(statusCode, message);
httpContext.Response.StatusCode = (int) statusCode;
await httpContext.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment