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

时间:2018-04-13 07:26:12

标签: elixir

我正在尝试使用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

1 个答案:

答案 0 :(得分:1)

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

try do
  HTTPoison.request!(...)
rescue
  HTTPoison.Error ->
    # the request raised an error
end