How to publish an error to an Absinthe Subscription

I have a long running task that downloads and parses a document. When the parsing is complete it publishes a subscription to notify the client is has completed:

    Absinthe.Subscription.publish(MyApp.Endpoint, parsed_document,
      new_document: "new_document:#{document.owner_id}"
    )

This works well, but sometimes there are errors with the download/parsing and I want to notify the client of any errors.

I was hoping to use Absinthe.Subscription.publish/3 to publish an error, but I can’t figure out a way to do that.

I was hoping to send something like this to any subscribed clients when an error occurs:

{
  "data": {
    "newDocument": null
  },
 "errors": [
   {
     "message": "Download Failed"
   }
 ]
}

Is it possible to send an error with Absinthe.Subscription.publish/3 or is there a different approach I could take?

Based on Ben response on slack (#absinthe-graphql)

simply return an error from the root subscription field resolver. by default you don’t need one but you could add one to look for specific published values and return an error

subscription do
  field :user_updated, :user do
    # other subscription setup stuff
    resolve fn %{user_updated: user}, _, _ ->
      case user do
        %User{} -> {:ok, user}
        {:error, reason} -> {:error, reason}
      end
    end
  end
end

then you can publish(PubSub, {:error, "bad things happened}, user_updated: topic)

3 Likes

Thanks so much for this!

I had to make one small change in the resolve function signature to get it to work.

subscription do
  field :user_updated, :user do
    # other subscription setup stuff
    resolve fn user, _, _ ->
      case user do
        %User{} -> {:ok, user}
        {:error, reason} -> {:error, reason}
      end
    end
  end
end
2 Likes