Patrick Angodung
Patrick Angodung

Reputation: 4831

Get the string inside the ActiveRecord::StatementInvalid rescue message

I'm trying to get the middle string inside the standard error message given by the rails rescue.

I have created BEFORE INSERT Triggers on my NuoDB database that further validates records on the database side and not just on the rails side.

What this trigger does is compare two dates when saving a record. If the first date is later than the 2nd date, the trigger will throw the following JDBC error string:

"INPUT_ERROR - Invalid Dates: date_2 must be greater than date_1"

Then I have the following code on the controller to save a record

def foo
    begin
      # save record
    rescue => e 
      flash[:notice] = e
    end
end

So saving a new record with incorrect dates would give a flash[:notice] of the error which would be something like

ActiveRecord::JDBCError: INPUT_ERROR - Invalid Dates: date_2 must be greater than date_1: INSERT INTO `table` (`date_1`, `date_2`) VALUES ('2016-03-23','2015-03-23')

What I would like to get is just the custom text I created. I would like to get the string without the "ActiveRecord::JDBCError:" string at the start and the SQL statement at the end.

So how can I get the text so that my flash[:notice] would just output this:

 "INPUT_ERROR - Invalid Dates: date_2 must be greater than date_1"

Upvotes: 1

Views: 1270

Answers (2)

Bobby Lawrence
Bobby Lawrence

Reputation: 106

To do what you want, you will either have to parse out the string yourself or change the error message that ActiveRecord generates when it encounters an exception.
The latter requires that you change the behavior of the "ActiveRecord::ConnectionAdapters::AbstractAdapter" class in either the "log" method (< 4.2.1) or the "translate_exception_class" method (>= 4.2.1) via a monkey patch or something. Example here:

https://gist.github.com/timraasveld/6c28bcc8b905818a98b349fe0eb73c5f

The current implementation of the method adds the original exception class name to the message of newly wrapped exception it throws (unless the subclassed adapter you are using overriddes this behavior itself)

Upvotes: 0

Evgenia Karunus
Evgenia Karunus

Reputation: 11202

use e.message instead of e, it will strip exception's class name.

Upvotes: 1

Related Questions