How to catch Plug.Parsers.ParseError

I’ve spent a while, read some posts to no effect :confused: How can I add a handler so that when malformed JSON is posted, I am not getting a standard HTML page, but my own JSON response (from ErrorView)?

Log fragment:

[debug] ** (Plug.Parsers.ParseError) malformed request, a Poison.SyntaxError exception was raised with message “Unexpected token at position 2: e”
(plug) lib/plug/parsers/json.ex:54: Plug.Parsers.JSON.decode/2
(plug) lib/plug/parsers.ex:221: Plug.Parsers.reduce/4

Did you manage to solve this @Przemek? I would also be interested in the answer.

Sort of… In endpoint.ex I replaced Poison with my own JSON decoder (btw Jason is faster) that wraps decode with try/catch. On parsing error it sets an error that I handle in controller… It works, but of course sucks. I am also interested in a better way :slight_smile:

1 Like