Skip to content

Commit

Permalink
Merge pull request #35 from edward-teixeira/Global_Exception_Handler_…
Browse files Browse the repository at this point in the history
…Middleware

Added custom global ExceptionHandlerMiddleware.
  • Loading branch information
AshrafAlam authored Jun 28, 2022
2 parents 60aeaa8 + f6fa878 commit d88ed70
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.Globalization;
using System.Net;
using System.Text.Json;

namespace Eisk.WebApi.Middlewares
{
internal record ApiError(string Id, int StatusCode, string Message)
{
public override string ToString() => JsonSerializer.Serialize(this);
}

public record ApiExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;

public ApiExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext ctx)
{
try
{
await _next(ctx).ConfigureAwait(false);
}
catch (Exception ex)
{
// Log Exception Message
// var message = string.Format(GetInnermostExceptionMessage(ex), CultureInfo.CurrentCulture);
await HandleExceptionAsync(ctx, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext ctx, Exception ex)
{
const int statusCode = (int) HttpStatusCode.InternalServerError;
ApiError apiError = new(
Guid.NewGuid().ToString(),
statusCode,
"Internal Server Error.");

ctx.Response.StatusCode = statusCode;
await ctx.Response.WriteAsync(apiError.ToString()).ConfigureAwait(false);
}

private string GetInnermostExceptionMessage(Exception ex)
=> ex.InnerException is not null ?
GetInnermostExceptionMessage(ex.InnerException) : ex.Message;
}
}
3 changes: 3 additions & 0 deletions WebApi/Eisk.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Eisk.DataServices.Interfaces;
using Eisk.DomainServices;
using Eisk.EFCore.Setup;
using Eisk.WebApi.Middlewares;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);
Expand Down Expand Up @@ -46,6 +47,8 @@

var app = builder.Build();

app.UseMiddleware<ApiExceptionHandlerMiddleware>();

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(options =>
Expand Down

0 comments on commit d88ed70

Please sign in to comment.