< Summary

Information
Class: TicTacToeApp.API.Middleware.ExceptionHandlerMiddleware
Assembly: TicTacToeApp.API
File(s): /home/runner/work/TicTacToe/TicTacToe/TicTacToeApp.API/MIddleware/ExceptionHandlerMiddleware.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 52
Coverable lines: 52
Total lines: 100
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 26
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
InvokeAsync()100%210%
ConvertExceptionAsync(...)0%702260%

File(s)

/home/runner/work/TicTacToe/TicTacToe/TicTacToeApp.API/MIddleware/ExceptionHandlerMiddleware.cs

#LineLine coverage
 1using System.Data.SqlTypes;
 2using System.Net;
 3using System.Text.Json;
 4using TicTacToeApp.API.Exceptions;
 5using TicTacToeApp.API.Response;
 6
 7namespace TicTacToeApp.API.Middleware;
 8
 9public sealed class ExceptionHandlerMiddleware
 10{
 11    private readonly RequestDelegate _next;
 12    private readonly ILogger<ExceptionHandlerMiddleware> _logger;
 13    private readonly IHostEnvironment _env;
 14
 015    public ExceptionHandlerMiddleware(
 016        RequestDelegate next,
 017        ILogger<ExceptionHandlerMiddleware> logger,
 018        IHostEnvironment env
 019    )
 20    {
 021        _env = env;
 022        _logger = logger;
 023        _next = next;
 024    }
 25
 26    // когда мы работает с middleware у нас есть доступ к контексту HttpContext
 27    public async Task InvokeAsync(HttpContext context)
 28    {
 29        try
 30        {
 31            // мы получим контекст http и передадим его дальше другому middleware вниз
 032            await _next(context);
 033        }
 034        catch (Exception ex)
 35        {
 036            _logger.LogError(ex, ex.Message);
 037            await ConvertExceptionAsync(context, ex);
 38        }
 039    }
 40
 41    private Task ConvertExceptionAsync(HttpContext context, System.Exception exception)
 42    {
 043        context.Response.ContentType = "application/json";
 044        var httpStatusCode = HttpStatusCode.InternalServerError;
 45
 046        var message = string.Empty;
 047        var messagedetail = string.Empty;
 48
 49        switch (exception)
 50        {
 51            case Npgsql.PostgresException ex:
 052                httpStatusCode = HttpStatusCode.InternalServerError;
 053                message = ex.Message;
 054                messagedetail = ex.StackTrace?.ToString();
 055                break;
 56            case BadHttpRequestException badRequestException:
 057                httpStatusCode = HttpStatusCode.BadRequest;
 058                message = badRequestException.Message;
 059                messagedetail = badRequestException.StackTrace?.ToString();
 060                break;
 61
 62            case NotFoundException ex:
 063                httpStatusCode = HttpStatusCode.NotFound;
 064                message = ex.Message;
 065                messagedetail = ex.StackTrace?.ToString();
 066                break;
 67
 68            case ArgumentException ex:
 069                httpStatusCode = HttpStatusCode.BadRequest;
 070                message = ex.Message;
 071                messagedetail = ex.StackTrace?.ToString();
 072                break;
 73
 74            case SqlTypeException sqlEx:
 075                httpStatusCode = HttpStatusCode.BadRequest;
 076                message = sqlEx.Message;
 077                messagedetail = sqlEx.StackTrace?.ToString();
 078                break;
 79
 80            case Exception ex:
 081                httpStatusCode = HttpStatusCode.InternalServerError;
 082                message = ex.Message;
 083                messagedetail = ex.StackTrace?.ToString();
 84                break;
 85        }
 86
 087        context.Response.StatusCode = (int)httpStatusCode;
 88
 089        var response = _env.IsDevelopment()
 090            ? new ErrorResponse(context.Response.StatusCode.ToString(), message, messagedetail)
 091            : new ErrorResponse(context.Response.StatusCode.ToString(), "Internal Server Error");
 92
 093        var options = new JsonSerializerOptions()
 094        {
 095            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
 096        };
 097        var result = JsonSerializer.Serialize(response, options);
 098        return context.Response.WriteAsync(result);
 99    }
 100}