Skip to content

Commit

Permalink
Fix error handling when writing to file during download (#390)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatanklosko authored Aug 8, 2024
1 parent 957ee59 commit f1c3fe9
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions lib/bumblebee/utils/http.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,7 @@ defmodule Bumblebee.Utils.HTTP do
end

defp download_receive(state, {_, {{_, 200, _}, _headers, body}}) do
case IO.binwrite(state.file, body) do
:ok ->
:ok

{:error, error} ->
{:error, "failed to write to file, reason: #{:file.format_error(error)}"}
end
safe_binwrite(state.file, body)
end

defp download_receive(_state, {_, {{_, status, _}, _headers, _body}}) do
Expand All @@ -90,7 +84,7 @@ defmodule Bumblebee.Utils.HTTP do
end

defp download_receive(state, {_, :stream, body_part}) do
case IO.binwrite(state.file, body_part) do
case safe_binwrite(state.file, body_part) do
:ok ->
part_size = byte_size(body_part)
state = update_in(state.size, &(&1 + part_size))
Expand All @@ -104,7 +98,7 @@ defmodule Bumblebee.Utils.HTTP do

{:error, error} ->
:httpc.cancel_request(state.request_id, :bumblebee)
{:error, "failed to write to file, reason: #{:file.format_error(error)}"}
{:error, error}
end
end

Expand All @@ -122,6 +116,15 @@ defmodule Bumblebee.Utils.HTTP do
end
end

defp safe_binwrite(file, iodata) do
try do
IO.binwrite(file, iodata)
catch
:error, error ->
{:error, "failed to write to file, reason: #{inspect(error)}"}
end
end

@doc """
Makes an HTTP request.
Expand Down

0 comments on commit f1c3fe9

Please sign in to comment.