发送HTTPoison请求!以一种尝试和捕捉方式的灵药

问题描述 投票:0回答:1

我正在尝试使用Elixir Dropbox包发送POST请求,但它非常简单

case ElixirDropbox.Files.upload(client, upload_image_path, image_path) do
  {{:status_code, _}, {:error, error}} -> Logger.debug "Error while uploading. Error: #{inspect error}"
  _ -> :noop
end

问题是:我正在使用的库是request!而不是request,并且在状态代码失败的情况下它没有给出任何响应它引发了timeout的异常

** (HTTPoison.Error) :timeout
    (httpoison) lib/httpoison.ex:66: HTTPoison.request!/5
    (elixir_dropbox) lib/elixir_dropbox.ex:36: ElixirDropbox.post_request/4
    (evercam_media) lib/evercam_media/snapshot_extractor/extractor.ex:132: 

我们如何处理这种情况?在trycatchrescue ?,

我只想做的是:如果有任何异常或失败,从Dropbox API,我想再次重试上传,让我们说5次尝试。

  defp upload_image("true", image_path, upload_image_path) do
    client = ElixirDropbox.Client.new(System.get_env["DROP_BOX_TOKEN"])
    case ElixirDropbox.Files.upload(client, upload_image_path, image_path) do
      {{:status_code, _}, {:error, error}} -> Logger.debug "Error while uploading. Error: #{inspect error}"
      _ -> :noop
    end
  end
elixir
1个回答
1
投票

您可以使用try / rescue来捕获此错误:

try do
  HTTPoison.request!(...)
rescue
  HTTPoison.Error ->
    # the request raised an error
end
© www.soinside.com 2019 - 2024. All rights reserved.