-
Notifications
You must be signed in to change notification settings - Fork 54
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #35 from edward-teixeira/Global_Exception_Handler_…
…Middleware Added custom global ExceptionHandlerMiddleware.
- Loading branch information
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
WebApi/Eisk.WebApi/Middlewares/Middlewares/ApiExceptionHandlerMiddleware.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters