Trying to handle an exception but unable to

I’m trying to handle the cases when Stripe returns an error.

I wonder, why all of these fail with the same error which I can’t handle:

1)

try do
    a1 = Stripe.Customers.create(email: stripe_email, source: stripe_token)
    IO.puts("ok")

catch
  x -> 
        IO.puts("errorrrrr #{x}")
end


2)
    a1 = Stripe.Customers.create(email: stripe_email, source: stripe_token)
    IO.puts("ok")

3)
    case Stripe.Customers.create(email: stripe_email, source: stripe_token) do
      {:ok, data} -> IO.puts("ok")
      {:error, data} -> IO.puts("error")
    end

The error is:

** (MatchError) no match of right hand side value: {:error, %HTTPoison.Error{id: nil, reason: :nxdomain}} 

which is cases by “Stripe.Customers.create(email: stripe_email, source: stripe_token)”

That is, it never gets to the point with “IO.puts(…)” and fails when calling “Stripe.Customers.create(…)”

If that error originates from inside Stripe you’re going to need to use rescue instead of catch. catch is for thrown values and exits, rescue is for errors (exceptions). In Elixir catch isn’t used for exceptions - and errors are raised, not thrown.

2 Likes