sheharyarn

sheharyarn

Handling Exceptions in Absinthe

The Issue

There are a lot of guides available for handling error tuples in Absinthe but next to zero for exceptions.

This is important because there are always unforseen issues which might raise an exception and return a response that will not conform to the graphql response/error spec. This can be especially problematic when GraphQL clients like apollo automatically batch requests, and an exception in one query will crash the whole BEAM web process causing all queries to fail.


Existing Approaches

My first thought was to wrap the resolvers in a try/rescue block using middleware and the only two links I came across, also suggested a similar approach:

  • Elixir Forum: How to use Absinthe.MiddleWare to catch exception?

    • @benwilson512 recommends replacing the Resolution middleware with a custom one that executes the resolver in a try block

    • This would not handle exceptions in other middleware (but maybe that’s how it should be)

  • Blog Post: Handling Elixir Exceptions in Absinthe using Middleware

    • Tries to do the same thing, but doesn’t follow the Absinthe.Middleware behaviour spec

    • Instead wraps all existing middleware in anonymous functions

    • We also lose insight into the enabled middleware and their configs when inspecting them because of this


My Solution

My approach is a bit inspired from the blog post, but I’ve tried to follow the behaviour and use middleware tuple spec instead of anonymous functions:

Middleware Definition:

defmodule MyApp.ExceptionMiddleware do
  @behaviour Absinthe.Middleware
  @default_error {:error, :internal_server_error}
  @default_config []

  @spec wrap(Absinthe.Middleware.spec()) :: Absinthe.Middleware.spec()
  def wrap(middleware_spec) do
    {__MODULE__, [handle: middleware_spec]}
  end

  @impl true
  def call(resolution, handle: middleware_spec) do
    execute(middleware_spec, resolution)
  rescue
    error ->
      Sentry.capture_exception(error, __STACKTRACE__)
      Absinthe.Resolution.put_result(resolution, @default_error)
  end

  # Handle all the ways middleware can be defined

  defp execute({{module, function}, config}, resolution) do
    apply(module, function, [resolution, config])
  end

  defp execute({module, config}, resolution) do
    apply(module, :call, [resolution, config])
  end

  defp execute(module, resolution) when is_atom(module) do
    apply(module, :call, [resolution, @default_config])
  end

  defp execute(fun, resolution) when is_function(fun, 2) do
    fun.(resolution, @default_config)
  end
end

Applying it in Schema:

The wrap/1 method is called on all query/mutation middleware

def middleware(middleware, _field, %{identifier: type}) when type in [:query, :mutation] do
  Enum.map(middleware, &ExceptionMiddleware.wrap/1)
end

Result:

Which converts them to this:

[
  {ExceptionMiddleware, handle: {AuthMiddleware, [access: :admin]}},
  {ExceptionMiddleware, handle: {{Resolution, :call}, &some_resolver/3}},
  {ExceptionMiddleware, handle: {Subscription, []}},
  {ExceptionMiddleware, handle: &anon_middleware/2},
]

Question(s)

I’m still not fully confident in my approach because this feels a bit hacky and a misuse of absinthe’s middleware. So, I’m interested in getting answers to a couple of questions:

  • What other possible approaches are there? Is using Absinthe middleware the right choice after all?
  • If so, does it make sense to wrap all middleware or just replace the Absinthe.Resolution middleware?
  • And what’s the canonical way of doing that?


Posted in parallel with this Stackoverflow Question.

Where Next?

Popular in Questions Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
hariharasudhan94
Lets say i have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => "XX...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42842 311
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35953 110
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement