diff --git a/lib/open_graph.ex b/lib/open_graph.ex index 4afdbd0..36d462b 100644 --- a/lib/open_graph.ex +++ b/lib/open_graph.ex @@ -46,8 +46,14 @@ defmodule OpenGraph do |> handle_response() end - defp handle_response({:ok, %Req.Response{status: status} = response}) when status in 200..299 do - {:ok, parse(response.body)} + defp handle_response({:ok, %Req.Response{status: status, body: body}}) + when status in 200..299 and is_binary(body) do + {:ok, parse(body)} + end + + defp handle_response({:ok, %Req.Response{status: status, body: body}}) + when status in 200..299 do + {:error, %OpenGraph.Error{reason: {:unexpected_format, body}}} end defp handle_response({:ok, %Req.Response{status: status}}) when status in 300..399 do diff --git a/lib/open_graph/error.ex b/lib/open_graph/error.ex index ce47a98..48ec92e 100644 --- a/lib/open_graph/error.ex +++ b/lib/open_graph/error.ex @@ -23,6 +23,10 @@ defmodule OpenGraph.Error do "unexpected response is received. HTTP status code: #{status_code}" end + defp format_reason({:unexpected_format, body}) do + "unexpected response format is received. body: #{inspect(body)}" + end + defp format_reason({:request_error, reason}) do "request error. reason: #{reason}" end diff --git a/test/open_graph_test.exs b/test/open_graph_test.exs index bd1865c..20aeee4 100644 --- a/test/open_graph_test.exs +++ b/test/open_graph_test.exs @@ -97,6 +97,17 @@ defmodule OpenGraphTest do end end + test "fetch!/1 raises exception for unexpected response format" do + data = %{"title" => "The Rock"} + Req.Test.stub(MyStub, &Req.Test.json(&1, data)) + + assert_raise Error, + "unexpected response format is received. body: #{inspect(data)}", + fn -> + fetch!("https://example.com/") + end + end + test "fetch!/1 raises exception for server downtime" do Req.Test.stub(MyStub, &Req.Test.transport_error(&1, :econnrefused))