refactor: Replace bang calls with error handling in Index LiveViews
- Replace Ash.get!/Ash.destroy! with Ash.get/Ash.destroy - Add case statements for Forbidden, NotFound, and generic errors - Display user-friendly flash messages for all error cases - Use Enum.map_join/3 for efficient error formatting
This commit is contained in:
parent
77ae5c4888
commit
a22081f288
5 changed files with 130 additions and 23 deletions
|
|
@ -43,11 +43,41 @@ defmodule MvWeb.UserLive.Index do
|
|||
|
||||
@impl true
|
||||
def handle_event("delete", %{"id" => id}, socket) do
|
||||
user = Ash.get!(Mv.Accounts.User, id, domain: Mv.Accounts)
|
||||
Ash.destroy!(user, domain: Mv.Accounts)
|
||||
actor = current_actor(socket)
|
||||
|
||||
updated_users = Enum.reject(socket.assigns.users, &(&1.id == id))
|
||||
{:noreply, assign(socket, :users, updated_users)}
|
||||
case Ash.get(Mv.Accounts.User, id, domain: Mv.Accounts, actor: actor) do
|
||||
{:ok, user} ->
|
||||
case Ash.destroy(user, domain: Mv.Accounts, actor: actor) do
|
||||
:ok ->
|
||||
updated_users = Enum.reject(socket.assigns.users, &(&1.id == id))
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:users, updated_users)
|
||||
|> put_flash(:info, gettext("User deleted successfully"))}
|
||||
|
||||
{:error, %Ash.Error.Forbidden{}} ->
|
||||
{:noreply,
|
||||
put_flash(
|
||||
socket,
|
||||
:error,
|
||||
gettext("You do not have permission to delete this user")
|
||||
)}
|
||||
|
||||
{:error, error} ->
|
||||
{:noreply, put_flash(socket, :error, format_error(error))}
|
||||
end
|
||||
|
||||
{:error, %Ash.Error.Query.NotFound{}} ->
|
||||
{:noreply, put_flash(socket, :error, gettext("User not found"))}
|
||||
|
||||
{:error, %Ash.Error.Forbidden{} = _error} ->
|
||||
{:noreply,
|
||||
put_flash(socket, :error, gettext("You do not have permission to access this user"))}
|
||||
|
||||
{:error, error} ->
|
||||
{:noreply, put_flash(socket, :error, format_error(error))}
|
||||
end
|
||||
end
|
||||
|
||||
# Selects one user in the list of users
|
||||
|
|
@ -108,4 +138,12 @@ defmodule MvWeb.UserLive.Index do
|
|||
defp toggle_order(:desc), do: :asc
|
||||
defp sort_fun(:asc), do: &<=/2
|
||||
defp sort_fun(:desc), do: &>=/2
|
||||
|
||||
defp format_error(%Ash.Error.Invalid{errors: errors}) do
|
||||
Enum.map_join(errors, ", ", fn %{message: message} -> message end)
|
||||
end
|
||||
|
||||
defp format_error(error) do
|
||||
inspect(error)
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue