Skip to content

Commit a3d639b

Browse files
Add print extension method for LanguageExt Errors (#33)
Closes #30
1 parent bda92e6 commit a3d639b

File tree

3 files changed

+80
-1
lines changed

3 files changed

+80
-1
lines changed

src/Dbosoft.Functional.Json/Dbosoft.Functional.Json.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>netstandard2.0</TargetFramework>
5-
<Nullable>enable</Nullable>
5+
<Nullable>enable</Nullable>
66
<PackageId>Dbosoft.Functional.Json</PackageId>
77
<Description>JSON support for LanguageExt NewType.</Description>
88
</PropertyGroup>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System;
2+
using LanguageExt.Common;
3+
4+
namespace Dbosoft.Functional;
5+
6+
#nullable enable
7+
8+
public static class ErrorExtensions
9+
{
10+
public static string Print(this Error error) =>
11+
error switch
12+
{
13+
ManyErrors manyErrors => string.Join(Environment.NewLine, manyErrors.Errors.Map(Print)),
14+
Exceptional exceptional => exceptional.ToException().ToString(),
15+
_ => error.Message + error.Inner.Map(inner => $"{Environment.NewLine}{Print(inner)}").IfNone(""),
16+
};
17+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
using LanguageExt.Common;
2+
3+
namespace Dbosoft.Functional.Tests;
4+
5+
public class ErrorExtensionsTests
6+
{
7+
[Fact]
8+
public void Print_ComplexHierarchy_ReturnsString()
9+
{
10+
Error error;
11+
try
12+
{
13+
throw new Exception("test exception");
14+
}
15+
catch (Exception ex)
16+
{
17+
error = Error.New("root error",
18+
Error.Many(
19+
Error.New("outer error",
20+
Error.New("inner error")),
21+
Error.New(ex)));
22+
}
23+
24+
var result = error.Print();
25+
result.Should().StartWith(
26+
"""
27+
root error
28+
outer error
29+
inner error
30+
System.Exception: test exception
31+
""");
32+
}
33+
34+
[Fact]
35+
public void Print_NestedException_ReturnsString()
36+
{
37+
Error error;
38+
try
39+
{
40+
try
41+
{
42+
throw new Exception("inner exception");
43+
}
44+
catch (Exception ex)
45+
{
46+
throw new Exception("outer exception", ex);
47+
}
48+
}
49+
catch (Exception ex)
50+
{
51+
error = Error.New("root error", Error.New(ex));
52+
}
53+
54+
var result = error.Print();
55+
result.Should().StartWith(
56+
"""
57+
root error
58+
System.Exception: outer exception
59+
---> System.Exception: inner exception
60+
""");
61+
}
62+
}

0 commit comments

Comments
 (0)