fix: log exception

This commit is contained in:
Polianin Nikita 2024-10-27 03:02:25 +03:00
parent ed99fce9b8
commit fc5ec1fd54

View File

@ -1,5 +1,6 @@
using FluentValidation; using FluentValidation;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Mirea.Api.DataAccess.Application.Common.Exceptions; using Mirea.Api.DataAccess.Application.Common.Exceptions;
using Mirea.Api.Dto.Responses; using Mirea.Api.Dto.Responses;
using Mirea.Api.Endpoint.Common.Exceptions; using Mirea.Api.Endpoint.Common.Exceptions;
@ -9,7 +10,7 @@ using System.Threading.Tasks;
namespace Mirea.Api.Endpoint.Configuration.Core.Middleware; namespace Mirea.Api.Endpoint.Configuration.Core.Middleware;
public class CustomExceptionHandlerMiddleware(RequestDelegate next) public class CustomExceptionHandlerMiddleware(RequestDelegate next, ILogger<CustomExceptionHandlerMiddleware> logger)
{ {
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
{ {
@ -23,7 +24,7 @@ public class CustomExceptionHandlerMiddleware(RequestDelegate next)
} }
} }
private static Task HandleExceptionAsync(HttpContext context, Exception exception) private Task HandleExceptionAsync(HttpContext context, Exception exception)
{ {
var code = StatusCodes.Status500InternalServerError; var code = StatusCodes.Status500InternalServerError;
var result = string.Empty; var result = string.Empty;
@ -48,12 +49,23 @@ public class CustomExceptionHandlerMiddleware(RequestDelegate next)
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
context.Response.StatusCode = code; context.Response.StatusCode = code;
if (string.IsNullOrEmpty(result)) if (!string.IsNullOrEmpty(result))
result = JsonSerializer.Serialize(new ErrorResponse() return context.Response.WriteAsync(result);
{
Error = exception.Message, string error;
Code = code if (code == StatusCodes.Status500InternalServerError)
}); {
error = "Internal Server Error";
logger.LogError("Internal server error: {Message}\nStackTrace:\n{StackTrace}", exception.Message, exception.StackTrace);
}
else
error = exception.Message;
result = JsonSerializer.Serialize(new ErrorResponse()
{
Error = error,
Code = code
});
return context.Response.WriteAsync(result); return context.Response.WriteAsync(result);
} }