Currently it is returning a single unintelligible chunk composed of multiple of these things glued one next to the other like this:
at ProyectX.Services.Service.Validate(IList 1 myParam) in C:\\Repositories\\projectx\\src\\ProyectX.Services\\Service.cs:line 116\r\n at ProyectX.Services.Service.Validate(IList 1 myParam) in C:\\Repositories\\projectx\\src\\ProyectX.Services\\Service.cs:line 116\r\n
Goal:
at ProyectX.Services.Service.Validate(IList 1 myParam) in C:\Repositories\projectx\src\ProyectX.Services\Service.cs:line 116
at ProyectX.Services.Service.Validate(IList 1 myParam) in C:\Repositories\projectx\src\ProyectX.Services\Service.cs:line 116
I tried with
Regex.Unescape(exception.StackTrace)
JsonSerializer.Serialize(exception.StackTrace, new JsonSerializerOptions() {WriteIndented = true });
The middleware is in Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ErrorHandlerMiddleware>();
Middleweare:
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using ProyectX.Domain.Exceptions;
using ProyectX.Domain.Models;
namespace ProyectX.API.Middleware
{
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IWebHostEnvironment env)
{
try
{
await _next(context);
}
catch (Exception exception)
{
var response = context.Response;
response.ContentType = "application/json";
switch (exception)
{
case InvalidOperationException:
response.StatusCode = (int)HttpStatusCode.BadRequest;
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
var details = new Dictionary<string, string>
{
{ "Message", exception.Message },
};
if (env.IsDevelopment())
{
details.Add("StackTrace", exception.StackTrace);
}
var errorResponse = new ErrorResponseModel(exception, details);
var result = JsonSerializer.Serialize(errorResponse);
await response.WriteAsync(result);
}
}
}
}
ErrorResponseModel
using System;
using System.Collections.Generic;
namespace ProyectX.Domain.Models
{
public class ErrorResponseModel
{
public ErrorResponseModel(Exception ex, Dictionary<string, string> details)
{
Type = ex.GetType().Name;
Details = details;
}
public string Type { get; set; }
public IDictionary<string, string> Details { get; set; }
}
}
