Skip to content

Instantly share code, notes, and snippets.

@edwinv
Last active December 19, 2015 13:09
Show Gist options
  • Save edwinv/5960407 to your computer and use it in GitHub Desktop.
Save edwinv/5960407 to your computer and use it in GitHub Desktop.
PostgreSQL exception library
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
class NotNullViolation < ActiveRecord::WrappedDatabaseException
end
class CheckViolation < ActiveRecord::WrappedDatabaseException
end
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def translate_exception(exception, message)
raise exception unless exception.respond_to?(:result)
case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
when UNIQUE_VIOLATION
RecordNotUnique.new(message, exception)
when FOREIGN_KEY_VIOLATION
InvalidForeignKey.new(message, exception)
# Custom error codes based on PostgreSQL documentation:
# http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
when '23502'
NotNullViolation.new(message, exception)
when '23514'
CheckViolation.new(message, exception)
else
super
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment