Skip to content

Instantly share code, notes, and snippets.

@Platonenkov
Created July 10, 2023 14:28
Show Gist options
  • Save Platonenkov/427ce96e3736f2fb236e725c0cb10620 to your computer and use it in GitHub Desktop.
Save Platonenkov/427ce96e3736f2fb236e725c0cb10620 to your computer and use it in GitHub Desktop.
Exception Handling Middleware
namespace StaffService.Dto
{
public class ErrorDto
{
public int StatusCode { get; set; }
public string Message { get; set; }
}
}
using StaffService.Dto;
using System.Net;
using System.Text.Json;
// Обработчик ошибок (промежуточное ПО чтобы не писать обработчики в контроллере для отлова ошибок)
// Все ошибки будут обрабатываться в одном месте...
namespace StaffService.Middlewares
{
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (KeyNotFoundException ex)
{
await HandleExceptionAsync(httpContext,
ex.Message,
HttpStatusCode.NotFound,
"It's impossible, but... Roberto NOT FOUND!!!");
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext,
ex.Message,
HttpStatusCode.InternalServerError,
"Internal server error");
}
}
private async Task HandleExceptionAsync(HttpContext context, string exMsg, HttpStatusCode httpStatusCode, string message)
{
_logger.LogError(exMsg);
HttpResponse response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)httpStatusCode;
ErrorDto errorDto = new()
{
Message = message,
StatusCode = (int)httpStatusCode
};
await response.WriteAsJsonAsync(errorDto);
}
}
}
//...
app.UseMiddleware<ExceptionHandlingMiddleware>();
//...
@Platonenkov
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment