devinus / poison

An incredibly fast, pure Elixir JSON library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Poison.decode\2 not responding with error when the result is not fit to the 'as' parameter

griffhun opened this issue · comments

defmodule Event do
  @type t :: %__MODULE__{}
  defstruct [:type, :created, :payload]
end

Possible Incorrect behaviour:
iex(4)> Poison.decode("1", as: %Event{})
{:ok, 1}

iex(8)> Poison.decode("\"apple\"", as: %Event{})
{:ok, "apple"}

Working as expected:
iex(6)> Poison.decode("alma", as: %Event{})
{:error, {:invalid, "a", 0}}

iex(12)> Poison.decode("{\"type\":\"t1\"}", as: %Event{})
{:ok, %Event{created: nil, payload: nil, type: "t1"}}

I'd also be interested in hearing whether this is planned functionality, a bug, etc. I'm working on writing a library to wrap an API and for some calls I can get either an appropriate document for that endpoint or an "error" response with a message as to why. I can't find a way to ask it to fail out when the document doesn't match the strut passed in via as:, so right now I have to do the conversion twice, poke around to see which case I'm dealing with and then return appropriately.