How to create custom Error with passing data

Category: Ruby :: Published at: 21.04.2022

Sometimes raising error is not enough. As probably you know, you can use command like this:

raise ActiveModel::StrictValidationFailed, "Some message"

This command will return 500 error on your website + it will log into your console the name of the error and message you passed in.

But it won't give you any context. This is big problem if for example you call API and your response is bad.
You want to know, what is happening there directly.

Fortunately there is some solution for it.

We can build special custom Error, which will give us data.

# frozen_string_literal: true

module Products
  class CommunicationError < StandardError
    attr_reader :data

    def initialize(data)
      @data = data

If you build Error like this, you can pass there data and it will be passed further.

         "Failed to connect with product API"

Whatever you will pass as an argument, it will be reported for example in Rollbar/Sentry.

- Click if you liked this article

Views: 265