summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHentioe <me@bluerain.io>2020-11-27 00:26:23 +0800
committerHentioe <me@bluerain.io>2020-11-27 00:26:23 +0800
commit4ed3b3b064afb8f30ba9b393990c3767678cb3e3 (patch)
treee10bd92070a2642c0faa996e6c18198d7a459430
parentAdd some models (diff)
The request fails and returns an error
-rw-r--r--lib/azure_ex/model.ex24
-rw-r--r--lib/azure_ex/request.ex16
2 files changed, 36 insertions, 4 deletions
diff --git a/lib/azure_ex/model.ex b/lib/azure_ex/model.ex
new file mode 100644
index 0000000..46f2dbb
--- /dev/null
+++ b/lib/azure_ex/model.ex
@@ -0,0 +1,24 @@
+defmodule AzureEx.Model do
+ @moduledoc false
+
+ defmodule ApiError do
+ @moduledoc false
+
+ defstruct [:code, :message]
+
+ @type t :: %__MODULE__{
+ code: String.t(),
+ message: String.t()
+ }
+ end
+
+ defmodule RequestError do
+ @moduledoc false
+
+ defstruct [:reason]
+
+ @type t :: %__MODULE__{
+ reason: atom()
+ }
+ end
+end
diff --git a/lib/azure_ex/request.ex b/lib/azure_ex/request.ex
index 97a4927..67cd5f4 100644
--- a/lib/azure_ex/request.ex
+++ b/lib/azure_ex/request.ex
@@ -4,11 +4,12 @@ defmodule AzureEx.Request do
"""
alias AzureEx.{Config, TokenHosting}
+ alias AzureEx.Model.{ApiError, RequestError}
@type method :: :get | :post | :put | :delete
@type data :: map
@type result :: integer | map
- @type error :: map
+ @type error :: ApiError.t() | RequestError.t()
@type httpoison_result :: {:ok, HTTPoison.Response.t()} | {:error, HTTPoison.Error.t()}
@spec call(binary, method, data) :: {:ok, result} | {:error, error}
@@ -16,21 +17,28 @@ defmodule AzureEx.Request do
method |> send(endpoint, data) |> handle_response()
end
- @spec handle_response({:ok, HTTPoison.Response.t()}) :: {:ok, result} | {:error, error}
+ @type request_result :: {:ok, HTTPoison.Response.t()} | {:error, HTTPoison.Error.t()}
+
+ @spec handle_response(request_result) :: {:ok, result} | {:error, error}
def handle_response({:ok, %HTTPoison.Response{body: body, status_code: status_code}}) do
if body == "" do
{:ok, status_code}
else
result = Jason.decode!(body, keys: :atoms)
+ error = result[:error]
- if result[:error] && result[:error][:code] do
- {:error, %{code: result[:error][:code], message: result[:error][:message]}}
+ if error && error[:code] do
+ {:error, %ApiError{code: error[:code], message: error[:message]}}
else
{:ok, result}
end
end
end
+ def handle_response({:error, %HTTPoison.Error{reason: reason}}) do
+ {:error, %RequestError{reason: reason}}
+ end
+
@data_content_type "application/json"
@spec send(method, String.t(), data) :: httpoison_result