Current section

Files

Jump to
yotsuba lib middleware response.ex
Raw

lib/middleware/response.ex

defmodule Yotsuba.Middleware.ResponseMiddleware do
@behaviour Tesla.Middleware
@moduledoc """
Custom middleware that extracts the body from a successful response or converts the body
to an `{:error, reason}` tuple in case the request failed.
"""
def call(env, next, _options) do
env
|> Tesla.run(next)
|> handle_response()
end
defp handle_response(next = %Tesla.Env{status: 200}) do
next.body
end
defp handle_response(_next = %Tesla.Env{status: 404}) do
{:error, "Not found"}
end
defp handle_response(_next) do
{:error, "Error making request"}
end
end