Search code examples
ruby-on-railsrubyerror-handlingrubygemsruby-on-rails-5

Is it possible to customise a existing error/exception in rails?


My controller is catching the following error in a observed case

#<ActiveRecord::RecordNotUnique: Mysql2:: Error: Duplicate entry 'xyz1' for key 'abc.xyz': INSERT INTO'abc' (<insert statement which is throwing the error>

I wanted to know if there is a way to customize this exception such that it also includes the existing entry because of which the error of duplication is being thrown..

It might seem redundant to modify an existing standard error/exception, but I need it to avoid repetition of same logic in every controller to handle this error in order to fulfill the requirement as stated above.

Update 1 Expected output:

Whenever the following exception is thrown, an alternate error message has to be sent as exception which will be something like this..

{Message: "Error caused due to Duplicate entry 'xyz1' for key 'abc.xyz'", existing_abc_with_same_xyz: Abc.find_by(xyz: "xyz1"}

Something like overriding/overloading the existing error statement.

There are many locations where this error is being handled because of Abc being a nested_attribute for many other resources... Because of which I will have to customise in every location, which I feel as redundant.


Solution

  • You can use validation. It provides human readable error in the model

    class Abc < ApplicationRecord
      validates :xyz, uniqueness: true
    end
    

    And then customize message in locales

    Also it's possible to use :message key

    validates :xyz,
      uniqueness: {
        message: ->(_, data) do 
          "Error caused due to Duplicate entry #{data[:value]} for key 'abc.xyz'. Existing Abc with same xyz: #{Abc.find_by(xyz: data[:value]}"
        end
      }
    

    Please see guide