Skip to content

Commit

Permalink
Merge pull request #17 from BennieCopeland/empty-body-bug
Browse files Browse the repository at this point in the history
Catch exception thrown by JsonTextReader when the request body is empty.
  • Loading branch information
MangelMaxime committed Jan 13, 2021
2 parents ba2a717 + fbbb8d8 commit 6b21620
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/ThothSerializer.fs
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,21 @@ type ThothSerializer (?caseStrategy : CaseStrategy, ?extra : ExtraCoders, ?skipN

static member ReadBodyRaw (ctx: HttpContext) =
task {
use stream = new System.IO.StreamReader(ctx.Request.Body, Utf8EncodingWithoutBom, true, DefaultBufferSize, true)
use jsonReader = new JsonTextReader(stream)
let! json = JValue.ReadFromAsync jsonReader
return json
try
use stream = new System.IO.StreamReader(ctx.Request.Body, Utf8EncodingWithoutBom, true, DefaultBufferSize, true)
use jsonReader = new JsonTextReader(stream)
let! json = JValue.ReadFromAsync jsonReader
return Ok json
with
| :? Newtonsoft.Json.JsonReaderException as ex ->
return Error("Given an invalid JSON: " + ex.Message)
}

static member ReadBody (ctx: HttpContext) (decoder: Decoder<'T>) =
task {
let! json = ThothSerializer.ReadBodyRaw ctx
return Decode.fromValue "$" decoder json
match! ThothSerializer.ReadBodyRaw ctx with
| Ok json -> return Decode.fromValue "$" decoder json
| Error e -> return Error e
}

static member ReadBodyUnsafe (ctx: HttpContext) (decoder: Decoder<'T>) =
Expand Down
10 changes: 10 additions & 0 deletions tests/ThothSerializer.fs
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,14 @@ let tests =

Expect.equal content json "Deserialization failure"
}

testTask "DeserializationWhenBodyIsEmpty" {
let host = createHost ()
use _ = host.StartAsync ()
let client = new HttpClient()
let! (response : HttpResponseMessage) = client.PostAsync("http://localhost:5000/", null)
let! content = response.Content.ReadAsStringAsync()

Expect.stringStarts content "Error while deserializing" "Deserialization exception handling failure"
}
]

0 comments on commit 6b21620

Please sign in to comment.