I would suggest changing a bit in your ErrorResponseModel
class so that your dictionary accept object type as value, like Dictionary<string, object>
. Here comes the idea, that you can both added string OR string array.
So for your tacktrace, you can split it multiple line using split by "
" and get a string array of it, that I can pass to my StackTrace value.
So lets come to your model:
public class ErrorResponseModel
{
public ErrorResponseModel(Exception ex, Dictionary<string, object> details)
{
Type = ex.GetType().Name;
Details = details;
}
public string Type { get; set; }
public IDictionary<string, object> Details { get; set; }
}
Here is the part that handle exception:
var details = new Dictionary<string, object>
{
{ "Message", exception.Message} ,
};
var lines = exception.StackTrace?.Split("
").Select(e => e.TrimStart());
details.Add("StackTrace", lines);
var errorResponse = new ErrorResponseModel(exception, details);
var result = JsonSerializer.Serialize(errorResponse, new JsonSerializerOptions() { WriteIndented = true });
All this return following out:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…