Created
July 10, 2023 14:28
-
-
Save Platonenkov/427ce96e3736f2fb236e725c0cb10620 to your computer and use it in GitHub Desktop.
Exception Handling Middleware
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
namespace StaffService.Dto | |
{ | |
public class ErrorDto | |
{ | |
public int StatusCode { get; set; } | |
public string Message { get; set; } | |
} | |
} |
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
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); | |
} | |
} | |
} |
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
//... | |
app.UseMiddleware<ExceptionHandlingMiddleware>(); | |
//... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.youtube.com/watch?v=RAcpAc0EYV0