Skip to content

Commit a3af3be

Browse files
committed
feat: catch error when cannot parse json input
1 parent d3ad88f commit a3af3be

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/Voxel.MiddyNet.HttpJsonBodyParserMiddleware/HttpJsonBodyParserMiddleware.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System;
12
using Amazon.Lambda.APIGatewayEvents;
23
using Newtonsoft.Json;
34
using System.Threading.Tasks;
@@ -8,7 +9,16 @@ public class HttpJsonBodyParserMiddleware<T> : ILambdaMiddleware<APIGatewayProxy
89
{
910
public Task Before(APIGatewayProxyRequest lambdaEvent, MiddyNetContext context)
1011
{
11-
var source = JsonConvert.DeserializeObject<T>(lambdaEvent.Body);
12+
T source;
13+
try
14+
{
15+
source = JsonConvert.DeserializeObject<T>(lambdaEvent.Body);
16+
}
17+
catch (JsonReaderException ex)
18+
{
19+
throw new Exception($"Error parsing \"{lambdaEvent.Body}\" to type {typeof(T)}");
20+
}
21+
1222
context.AdditionalContext.Add("Body", source);
1323
return Task.CompletedTask;
1424
}

test/Voxel.MiddyNet.HttpJsonBodyParserMiddleware.Tests/HttpJsonBodyParserMiddlewareShould.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,22 @@ public async Task ProcessTheJsonRequest()
2929
context.AdditionalContext.ContainsKey("Body").Should().BeTrue();
3030
context.AdditionalContext["Body"].Should().BeEquivalentTo(expectation);
3131
}
32+
33+
[Fact]
34+
public async Task ErrorWhenJsonNotMapsToObject()
35+
{
36+
var context = new MiddyNetContext(Substitute.For<ILambdaContext>());
37+
var expectation = new TestObject("bar");
38+
var source = "Not Mapped object" + JsonConvert.SerializeObject(expectation);
39+
var request = new APIGatewayProxyRequest()
40+
{
41+
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } },
42+
Body = source
43+
};
44+
var middleware = new HttpJsonBodyParserMiddleware<TestObject>();
45+
Action action = () => middleware.Before(request, context);
46+
47+
action.Should().Throw<Exception>().WithMessage($"Error parsing \"{source}\" to type {typeof(TestObject)}");
48+
}
3249
}
3350
}

0 commit comments

Comments
 (0)