How to access database error information when using Rails and Postgres

I use find_by_sql to connect to the Postgres database and execute the database function. The database function executes a series of SQL statements and, if necessary, throws exceptions.

How to block the error code and the error message raised by the Postgres function in Rails?

def self.validate_email(systemuserid, emailaddress)
  begin
    result = (self.find_by_sql(["SELECT fn_systemuser_validate_email(?, ?) AS returncode", 
                                systemuserid, emailaddress])).first
  rescue => err
    # I want to get access to the error code and error message here and act accordingly
    # errno = ??
    # errmsg = ??
    if errno == 10000
    end
  end
  return result[:returncode]
end

I started by trying to find this information in the connection object - there is no such luck.

Any help is greatly appreciated.

+5
source share
4 answers

Currently, an active recording replaces the original error with an internal one, without transmitting the original with a new error. I can’t understand why anyone would like this.

So, the only solution right now is the monkey patch;)

module ActiveRecord
  module ConnectionAdapters
    class AbstractAdapter
      def translate_exception(e, message)
        ActiveRecord::WrappedDatabaseException.new(message,e)
      end

      # Replaces
      # def translate_exception(e, message)
      #   # override in derived class
      #   ActiveRecord::StatementInvalid.new(message)
      # end
    end
  end
end

_.

def self.validate_email(systemuserid, emailaddress)
  begin 
    result = (self.find_by_sql(["SELECT fn_systemuser_validate_email(?, ?) AS returncode", systemuserid, emailaddress])).first
  rescue ActiveRecord::WrappedDatabaseException => e

    pgerror = e.original_exception

    # Exact api depends on PG version, check the docs for your version.
    puts "Doing my stuff: #{pgerror.result.result_error_message}"

  end
end

pg 0.11 Rails 3.0.9. , .

+3

, , :

errmsg = YourModel.errors [0].full_messages

0

(9 !), - .

, (, ), , ( http://deveiate.org/code/pg/PG/Result.html) :

rescue ActiveRecord::WrappedDatabaseException => e

  pgerror = e.original_exception
  sqlstate = pgerror.result.error_field(PG::Result::PG_DIAG_SQLSTATE )
end
0

.cause.

begin
  # whatever.
rescue => err
  p err.cause
end
0

All Articles