Skip to content

Commit

Permalink
check response format error
Browse files Browse the repository at this point in the history
  • Loading branch information
goofansu committed Sep 1, 2024
1 parent f52cb53 commit e13a19f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/open_graph.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lib/open_graph/error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions test/open_graph_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down

0 comments on commit e13a19f

Please sign in to comment.