Skip to content

Commit

Permalink
Include RPC server stack trace in RemoteInvocationException.ToString()
Browse files Browse the repository at this point in the history
It isn't always possible to do, but when the server provides a `CommonErrorData` object, we certainly can do it.
I endeavored to copy the string format that .NET uses for its own exception formatting, including for inner exceptions.

Closes microsoft#369
  • Loading branch information
AArnott committed Dec 4, 2019
1 parent 08648a0 commit 46a0674
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/StreamJsonRpc/Exceptions/RemoteInvocationException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
namespace StreamJsonRpc
{
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using StreamJsonRpc.Protocol;

Expand Down Expand Up @@ -83,5 +85,56 @@ protected RemoteInvocationException(
/// The default implementation of this method produces a <see cref="CommonErrorData"/> object.
/// </remarks>
public object? DeserializedErrorData { get; }

/// <inheritdoc/>
public override string ToString()
{
string result = base.ToString();

CommonErrorData? errorData = this.DeserializedErrorData as CommonErrorData;
if (errorData != null)
{
var builder = new StringBuilder(base.ToString());
builder.AppendLine();
builder.AppendLine("RPC server exception:");
builder.AppendLine($"{errorData.TypeName}: {errorData.Message}");
if (errorData.Inner is object)
{
ContributeInnerExceptionDetails(builder, errorData.Inner);
}

ContributeStackTrace(builder, errorData);
result = builder.ToString();
}

return result;
}

private static void ContributeInnerExceptionDetails(StringBuilder builder, CommonErrorData errorData)
{
builder.AppendLine($" ---> {errorData.TypeName}: {errorData.Message}");
if (errorData.Inner is object)
{
ContributeInnerExceptionDetails(builder, errorData.Inner);
}

ContributeStackTrace(builder, errorData);

builder.AppendLine(" --- End of inner exception stack trace ---");
}

private static void ContributeStackTrace(StringBuilder builder, CommonErrorData errorData)
{
if (errorData.StackTrace != null)
{
using (var sr = new StringReader(errorData.StackTrace))
{
while (sr.ReadLine() is string line)
{
builder.AppendLine($" {line}");
}
}
}
}
}
}

0 comments on commit 46a0674

Please sign in to comment.