Rendering error page in LiveView after async task returns error

77 Views Asked by At

Is there a better way to make this work?

I want do some asynchronous work in a Task in LiveView. If the result is an error condition, I want to show an error page to the end user instead of the main LiveView page. Here is what I am currently doing:

  1. Call an async Task to do some work via Task.Supervisor.async_nolink/3 in handle_params/3

  2. Use handle_info/2 to listen for the result. If the result is an error, I redirect to the root page "/" using Phoenix.LiveView.redirect/2

  3. I have an if statement in handle_param/2 that says:

    if result_of_async_workflow == :error do
      raise UnknownErrorPage
    end
    

This displays the correct error page to the user.

Is the only way to accomplish this workflow? I tried raise UnknownErrorPage in handle_info/2, but that didn't work.

1

There are 1 best solutions below

1
On

try with this, this is a handle event function that invokes an anonymous function that redirect to another page

 def handle_event("do_task", %{"id" => id}, socket) do
    Task.async(fn -> async_task(id) end)

    {:noreply, socket}
  end

  defp async_task(id) do

    {:ok, redirect(socket, to: "/otra_pagina")}
  end