Home > front end >  Rails 6 proper rescue from error and fetch error message
Rails 6 proper rescue from error and fetch error message

Time:10-05

In my Rails 6 app I want to handle the situation where the external API returns me an error and I passed it to the Failure method (it's a dry-monad method).

def call
  response = api.check_applicant_status(id: applicant_id, options: options)
rescue Errors::BadRequestError => e
  e.message

  result(response: response, error: e.message)
end

attr_reader :applicant_id

private

def result(response:, error:)
  if response.present?
    Success(response)
  else
    Failure(error)
  end
end

The above code will only work if an error occurs. In happy path (where there will be proper response) the whole class will return a result from response variable (a hash) and won't even touch the result method.

I think the rescue should be at the end of each method (that's the convention I guess) but in my case it will give an error of undefined local variable or method 'e in case of happy path.

What is the right way to pass an error message to Failure in case of an error and to pass the result (hash) to Success in case of a happy path?

CodePudding user response:

Why do you need the private method? Assume success unless you rescue, then assume error right?

def call
  response = api.check_applicant_status(id: applicant_id, options: options)
  Success(response)
rescue Errors::BadRequestError => e
  Failure(e.message)
end
  • Related