Skip to content

Commit

Permalink
Respond with HTTP 400 if the request body cannot be deserialized
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaliumhexacyanoferrat committed Nov 23, 2023
1 parent c12cbbe commit e33b053
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
10 changes: 9 additions & 1 deletion Modules/Reflection/MethodHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,15 @@ public MethodHandler(IHandler parent, MethodInfo method, MethodRouting routing,
throw new ProviderException(ResponseStatus.BadRequest, "Request body expected");
}

targetArguments[i] = await deserializer.DeserializeAsync(request.Content, par.ParameterType);
try
{
targetArguments[i] = await deserializer.DeserializeAsync(request.Content, par.ParameterType);
}
catch (Exception e)
{
throw new ProviderException(ResponseStatus.BadRequest, "Failed to deserialize request body", e);
}

continue;
}
}
Expand Down
48 changes: 48 additions & 0 deletions Testing/Modules/Conversion/ErrorHandlingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

using GenHTTP.Modules.Functional;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GenHTTP.Testing.Acceptance.Modules.Conversion
{

[TestClass]
public class ErrorHandlingTests
{

#region Supporting data structures

record class MyEntity(string Data);

#endregion

#region Tests

[TestMethod]
public async Task UndeserializableBodyReturnsWithBadRequest()
{
var inline = Inline.Create()
.Post("/t", (MyEntity entity) => entity.Data);

using var runner = TestRunner.Run(inline);

using var request = runner.GetRequest("/t");

request.Method = HttpMethod.Post;

request.Content = new StringContent("I cannot be deserialized", null, "application/json");
request.Content.Headers.ContentType = new("application/json");

using var response = await runner.GetResponse(request);

Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
}

#endregion

}

}

0 comments on commit e33b053

Please sign in to comment.