forked from aelij/AsyncFriendlyStackTrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Example3_BadSerialization.cs
43 lines (40 loc) · 1.4 KB
/
Example3_BadSerialization.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace AsyncFriendlyStackTrace.Test
{
internal class Example3_BadSerialization : IExample
{
public async Task Run()
{
try
{
await new Example1().Run();
}
catch (Exception e)
{
PrepareException(e);
var serializedException = SerializeAndDeserializeException(e);
throw new AggregateException(serializedException);
}
}
protected virtual void PrepareException(Exception exception)
{
// do nothing
}
private static Exception SerializeAndDeserializeException(Exception e)
{
using (var stream = new MemoryStream())
{
// The caveat of using PrepareForAsyncSerialization is that it adds items
// to the exception's Data dictionary, which can't be serialized by default using DCS.
// Thus you must specify the dictionary's (internal) type as a known type...
var serializer = new DataContractSerializer(e.GetType(), new[] { e.Data.GetType() });
serializer.WriteObject(stream, e);
stream.Position = 0;
return (Exception)serializer.ReadObject(stream);
}
}
}
}