【发布时间】:2021-03-19 11:17:06
【问题描述】:
我正在使用 JsonConvert.SerializeObject 在服务器上序列化 Exception,然后编码为 byte[] 并在客户端反序列化使用 JsonConvert.DeserializeObject。到目前为止一切正常......问题是当我抛出 Exception 被替换的堆栈跟踪时,让我演示一下:
public void HandleException(RpcException exp)
{
// Get the exception byte[]
string exceptionString = exp.Trailer.GetBytes("exception-bin");
// Deserialize the exception
Exception exception = JsonConvert.DeserializeObject<Exception>(exceptionString, new
JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
// Log the Exception: The stacktrace is correct. Ex.: at ServerMethod()
Console.WriteLine(exception);
// Throw the same Exception: The stacktrace is changed. Ex.: at HandleException()
ExceptionDispatchInfo.Capture(exception).Throw();
}
【问题讨论】:
-
很遗憾,不,我使用的解决方案与建议的链接相同。
-
从网络服务器传回一个完整的异常可能是个坏主意,因为它暴露了客户端可能不知道的细节
-
server 异常的堆栈跟踪在客户端上毫无意义。如果您需要记录异常,请在服务器上执行此操作。此外,此时您甚至没有异常 - 阻止正确执行程序的错误。您有一个从远程调用返回的数据对象,您的程序已准备好处理该对象。将该数据对象视为数据,而不是例外
-
嗯,如果您反序列化
Exception并设置JsonSerializerSettings.Context = new StreamingContext(StreamingContextStates.CrossAppDomain),那么当抛出异常时,反序列化的异常回溯将附加到当前回溯。见dotnetfiddle.net/QUYHls。够了吗?
标签: c# exception json.net grpc