Skip to content

fix: Custom exception JSON converter #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace AWS.Lambda.Powertools.Logging.Internal.Converters;

/// <summary>
/// Converts an byte[] to JSON.
/// </summary>
internal class ByteArrayConverter : JsonConverter<byte[]>
{
/// <summary>
/// Converter throws NotSupportedException. Deserializing ByteArray is not allowed.
/// </summary>
/// <param name="reader">Reference to the JsonReader</param>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <param name="options">The Json serializer options.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException("Deserializing ByteArray is not allowed");
}

/// <summary>
/// Write the exception value as JSON.
/// </summary>
/// <param name="writer">The unicode JsonWriter.</param>
/// <param name="values">The byte array.</param>
/// <param name="options">The JsonSerializer options.</param>
public override void Write(Utf8JsonWriter writer, byte[] values, JsonSerializerOptions options)
{
if (values == null)
{
writer.WriteNullValue();
}
else
{
writer.WriteStartArray();

foreach (var value in values)
{
writer.WriteNumberValue(value);
}

writer.WriteEndArray();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace AWS.Lambda.Powertools.Logging.Internal.Converters;

/// <summary>
/// JsonConvert to handle the AWS SDK for .NET custom enum classes that derive from the class called ConstantClass.
/// </summary>
public class ConstantClassConverter : JsonConverter<object>
{
private static readonly HashSet<string> ConstantClassNames = new()
{
"Amazon.S3.EventType",
"Amazon.DynamoDBv2.OperationType",
"Amazon.DynamoDBv2.StreamViewType"
};

/// <summary>
/// Check to see if the type is derived from ConstantClass.
/// </summary>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <returns>True if the type is derived from ConstantClass, False otherwise.</returns>
public override bool CanConvert(Type typeToConvert)
{
return ConstantClassNames.Contains(typeToConvert.FullName);
}

/// <summary>
/// Converter throws NotSupportedException. Deserializing ConstantClass is not allowed.
/// </summary>
/// <param name="reader">Reference to the JsonReader</param>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <param name="options">The Json serializer options.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException("Deserializing ConstantClass is not allowed");
}

/// <summary>
/// Write the ConstantClass instance as JSON.
/// </summary>
/// <param name="writer">The unicode JsonWriter.</param>
/// <param name="value">The exception instance.</param>
/// <param name="options">The JsonSerializer options.</param>
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace AWS.Lambda.Powertools.Logging.Internal.Converters;

/// <summary>
/// Converts an exception to JSON.
/// </summary>
internal class ExceptionConverter : JsonConverter<Exception>
{
/// <summary>
/// Determines whether the type can be converted.
/// </summary>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <returns>True if the type can be converted, False otherwise.</returns>
public override bool CanConvert(Type typeToConvert)
{
return typeof(Exception).IsAssignableFrom(typeToConvert);
}

/// <summary>
/// Converter throws NotSupportedException. Deserializing Exception is not allowed.
/// </summary>
/// <param name="reader">Reference to the JsonReader</param>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <param name="options">The Json serializer options.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public override Exception Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException("Deserializing Exception is not allowed");
}

/// <summary>
/// Write the exception value as JSON.
/// </summary>
/// <param name="writer">The unicode JsonWriter.</param>
/// <param name="value">The exception instance.</param>
/// <param name="options">The JsonSerializer options.</param>
public override void Write(Utf8JsonWriter writer, Exception value, JsonSerializerOptions options)
{
var exceptionType = value.GetType();
var properties = exceptionType.GetProperties()
.Where(prop => prop.Name != nameof(Exception.TargetSite))
.Select(prop => new { prop.Name, Value = prop.GetValue(value) });

if (options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull)
properties = properties.Where(prop => prop.Value != null);

var props = properties.ToArray();
if (!props.Any())
return;

writer.WriteStartObject();
writer.WriteString(ApplyPropertyNamingPolicy("Type", options), exceptionType.FullName);

foreach (var prop in props)
{
switch (prop.Value)
{
case IntPtr intPtr:
writer.WriteNumber(ApplyPropertyNamingPolicy(prop.Name, options), intPtr.ToInt64());
break;
case UIntPtr uIntPtr:
writer.WriteNumber(ApplyPropertyNamingPolicy(prop.Name, options), uIntPtr.ToUInt64());
break;
case Type propType:
writer.WriteString(ApplyPropertyNamingPolicy(prop.Name, options), propType.FullName);
break;
default:
writer.WritePropertyName(ApplyPropertyNamingPolicy(prop.Name, options));
JsonSerializer.Serialize(writer, prop.Value, options);
break;
}
}

writer.WriteEndObject();
}

/// <summary>
/// Applying the property naming policy to property name
/// </summary>
/// <param name="propertyName">The name of the property</param>
/// <param name="options">The JsonSerializer options.</param>
/// <returns></returns>
private static string ApplyPropertyNamingPolicy(string propertyName, JsonSerializerOptions options)
{
return !string.IsNullOrWhiteSpace(propertyName) && options?.PropertyNamingPolicy is not null
? options.PropertyNamingPolicy.ConvertName(propertyName)
: propertyName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace AWS.Lambda.Powertools.Logging.Internal.Converters;

/// <summary>
/// Handles converting MemoryStreams to base 64 strings.
/// </summary>
internal class MemoryStreamConverter : JsonConverter<MemoryStream>
{
/// <summary>
/// Converter throws NotSupportedException. Deserializing MemoryStream is not allowed.
/// </summary>
/// <param name="reader">Reference to the JsonReader</param>
/// <param name="typeToConvert">The type which should be converted.</param>
/// <param name="options">The Json serializer options.</param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public override MemoryStream Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException("Deserializing MemoryStream is not allowed");
}

/// <summary>
/// Write the MemoryStream as a base 64 string.
/// </summary>
/// <param name="writer">The unicode JsonWriter.</param>
/// <param name="value">The MemoryStream instance.</param>
/// <param name="options">The JsonSerializer options.</param>
public override void Write(Utf8JsonWriter writer, MemoryStream value, JsonSerializerOptions options)
{
writer.WriteStringValue(Convert.ToBase64String(value.ToArray()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using AWS.Lambda.Powertools.Common;
using AWS.Lambda.Powertools.Logging.Internal.Converters;
using Microsoft.Extensions.Logging;

namespace AWS.Lambda.Powertools.Logging.Internal;
Expand Down Expand Up @@ -93,6 +95,18 @@ internal class LoggingAspectHandler : IMethodAspectHandler
/// Specify to clear Lambda Context on exit
/// </summary>
private bool _clearLambdaContext;

/// <summary>
/// The JsonSerializer options
/// </summary>
private static JsonSerializerOptions _jsonSerializerOptions;

/// <summary>
/// Get JsonSerializer options.
/// </summary>
/// <value>The current configuration.</value>
private static JsonSerializerOptions JsonSerializerOptions =>
_jsonSerializerOptions ??= BuildJsonSerializerOptions();

/// <summary>
/// Initializes a new instance of the <see cref="LoggingAspectHandler" /> class.
Expand Down Expand Up @@ -259,6 +273,22 @@ private void CaptureLambdaContext(AspectEventArgs eventArgs)
_systemWrapper.LogLine(
"Skipping Lambda Context injection because ILambdaContext context parameter not found.");
}

/// <summary>
/// Builds JsonSerializer options.
/// </summary>
private static JsonSerializerOptions BuildJsonSerializerOptions()
{
var jsonOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
jsonOptions.Converters.Add(new ByteArrayConverter());
jsonOptions.Converters.Add(new ExceptionConverter());
jsonOptions.Converters.Add(new MemoryStreamConverter());
jsonOptions.Converters.Add(new ConstantClassConverter());
return jsonOptions;
}

/// <summary>
/// Captures the correlation identifier.
Expand Down Expand Up @@ -286,7 +316,7 @@ private void CaptureCorrelationId(object eventArg)
try
{
var correlationId = string.Empty;
var jsonDoc = JsonDocument.Parse(JsonSerializer.Serialize(eventArg));
var jsonDoc = JsonDocument.Parse(JsonSerializer.Serialize(eventArg, JsonSerializerOptions));
var element = jsonDoc.RootElement;

for (var i = 0; i < correlationIdPaths.Length; i++)
Expand Down
Loading