| 1 |
:-( |
defmodule DaProductAppWeb.FallbackController do |
| 2 |
|
@moduledoc """ |
| 3 |
|
Translates controller action results into valid `Plug.Conn` responses. |
| 4 |
|
""" |
| 5 |
|
|
| 6 |
:-( |
use DaProductAppWeb, :controller |
| 7 |
|
|
| 8 |
|
# This clause handles when an action returns {:error, %Ecto.Changeset{}}. |
| 9 |
|
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do |
| 10 |
|
conn |
| 11 |
|
|> put_status(:unprocessable_entity) |
| 12 |
:-( |
|> json(%{ |
| 13 |
|
success: false, |
| 14 |
|
error: "validation_failed", |
| 15 |
|
errors: translate_errors(changeset), |
| 16 |
|
message: "Validation failed" |
| 17 |
|
}) |
| 18 |
|
end |
| 19 |
|
|
| 20 |
|
# This clause handles when an action returns {:error, :not_found}. |
| 21 |
|
def call(conn, {:error, :not_found}) do |
| 22 |
|
conn |
| 23 |
|
|> put_status(:not_found) |
| 24 |
:-( |
|> json(%{ |
| 25 |
|
success: false, |
| 26 |
|
error: "not_found", |
| 27 |
|
message: "Resource not found" |
| 28 |
|
}) |
| 29 |
|
end |
| 30 |
|
|
| 31 |
|
# This clause handles when an action returns {:error, :unauthorized}. |
| 32 |
|
def call(conn, {:error, :unauthorized}) do |
| 33 |
|
conn |
| 34 |
|
|> put_status(:unauthorized) |
| 35 |
:-( |
|> json(%{ |
| 36 |
|
success: false, |
| 37 |
|
error: "unauthorized", |
| 38 |
|
message: "Access denied" |
| 39 |
|
}) |
| 40 |
|
end |
| 41 |
|
|
| 42 |
|
# This clause handles when an action returns {:error, reason}. |
| 43 |
|
def call(conn, {:error, reason}) do |
| 44 |
|
conn |
| 45 |
|
|> put_status(:internal_server_error) |
| 46 |
:-( |
|> json(%{ |
| 47 |
|
success: false, |
| 48 |
|
error: "internal_error", |
| 49 |
|
message: format_error_reason(reason) |
| 50 |
|
}) |
| 51 |
|
end |
| 52 |
|
|
| 53 |
|
# This clause handles when the action does not return what we expect. |
| 54 |
|
def call(conn, _other) do |
| 55 |
|
conn |
| 56 |
|
|> put_status(:internal_server_error) |
| 57 |
:-( |
|> json(%{ |
| 58 |
|
success: false, |
| 59 |
|
error: "unknown_error", |
| 60 |
|
message: "An unexpected error occurred" |
| 61 |
|
}) |
| 62 |
|
end |
| 63 |
|
|
| 64 |
|
# --- helpers --- |
| 65 |
|
defp translate_errors(changeset) do |
| 66 |
:-( |
Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} -> |
| 67 |
:-( |
Enum.reduce(opts, msg, fn {key, value}, acc -> |
| 68 |
:-( |
String.replace(acc, "%{#{key}}", to_string(value)) |
| 69 |
|
end) |
| 70 |
|
end) |
| 71 |
|
end |
| 72 |
|
|
| 73 |
:-( |
defp format_error_reason(reason) when is_binary(reason), do: reason |
| 74 |
:-( |
defp format_error_reason(reason), do: inspect(reason) |
| 75 |
|
end |