Skip to content

Use Jason.encode! when sending errors #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions lib/twirp/plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ defmodule Twirp.Plug do
Telemetry.stop(:call, start, metadata)

conn
|> put_resp_content_type(env.content_type)
|> put_resp_content_type(env.content_type, nil)
|> send_resp(200, resp)
|> halt()
else
Expand Down Expand Up @@ -279,11 +279,10 @@ defmodule Twirp.Plug do
end

defp send_error(conn, error) do
content_type = Encoder.type(:json)
body = Encoder.encode(error, nil, content_type)
body = Jason.encode!(error)

conn
|> put_resp_content_type(content_type)
|> put_resp_content_type("application/json", nil)
|> send_resp(Error.code_to_status(error.code), body)
|> halt()
end
Expand Down
19 changes: 14 additions & 5 deletions test/twirp/plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,9 @@ defmodule Twirp.PlugTest do
end

def content_type(conn) do
conn.resp_headers
|> Enum.find_value(fn {h, v} -> if h == "content-type", do: v, else: false end)
|> String.split(";") # drop the charset if there is one
|> Enum.at(0)
Enum.find_value(conn.resp_headers, fn {h, v} ->
if h == "content-type", do: v, else: false
end)
end

def call(req, opts \\ @opts) do
Expand Down Expand Up @@ -112,6 +111,16 @@ defmodule Twirp.PlugTest do
assert conn == req
end

test "does not include the __exception__ field" do
req = conn(:get, "/twirp/plug.test.Haberdasher/MakeHat")
conn = call(req)

assert conn.status == 404
assert content_type(conn) == "application/json"
body = Jason.decode!(conn.resp_body)
refute Map.has_key?(body, "__exception__")
end

test "not a POST" do
req = conn(:get, "/twirp/plug.test.Haberdasher/MakeHat")
conn = call(req)
Expand Down Expand Up @@ -299,7 +308,7 @@ defmodule Twirp.PlugTest do
resp = Jason.decode!(conn.resp_body)
assert resp["code"] == "internal"
assert resp["msg"] == "Blow this ish up"
assert resp["meta"] == %{}
refute Map.has_key?(resp, "meta")
end

describe "before" do
Expand Down