errors.rb 8.4 KB
Newer Older
1
module ActiveRecord
R
Rizwan Reza 已提交
2 3 4

  # = Active Record Errors
  #
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
  # Generic Active Record exception class.
  class ActiveRecordError < StandardError
  end

  # Raised when the single-table inheritance mechanism fails to locate the subclass
  # (for example due to improper usage of column that +inheritance_column+ points to).
  class SubclassNotFound < ActiveRecordError #:nodoc:
  end

  # Raised when an object assigned to an association has an incorrect type.
  #
  #   class Ticket < ActiveRecord::Base
  #     has_many :patches
  #   end
  #
  #   class Patch < ActiveRecord::Base
  #     belongs_to :ticket
  #   end
  #
  #   # Comments are not patches, this assignment raises AssociationTypeMismatch.
A
AvnerCohen 已提交
25
  #   @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
26 27 28 29 30 31 32
  class AssociationTypeMismatch < ActiveRecordError
  end

  # Raised when unserialized object's type mismatches one specified for serializable field.
  class SerializationTypeMismatch < ActiveRecordError
  end

33 34
  # Raised when adapter not specified on connection (or configuration file
  # +config/database.yml+ misses adapter field).
35 36 37
  class AdapterNotSpecified < ActiveRecordError
  end

38 39
  # Raised when Active Record cannot find database adapter specified in
  # +config/database.yml+ or programmatically.
40 41 42
  class AdapterNotFound < ActiveRecordError
  end

43 44
  # Raised when connection to the database could not been established (for
  # example when +connection=+ is given a nil object).
45 46 47 48 49
  class ConnectionNotEstablished < ActiveRecordError
  end

  # Raised when Active Record cannot find record by given id or set of ids.
  class RecordNotFound < ActiveRecordError
50 51 52 53 54 55 56 57 58
    attr_reader :model, :primary_key, :id

    def initialize(message = nil, model = nil, primary_key = nil, id = nil)
      @primary_key = primary_key
      @model = model
      @id = id

      super(message)
    end
59 60 61 62 63
  end

  # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
  # saved because record is invalid.
  class RecordNotSaved < ActiveRecordError
64 65
    attr_reader :record

66
    def initialize(message, record = nil)
67
      @record = record
68
      super(message)
69
    end
70 71
  end

72
  # Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
73 74 75 76 77 78 79
  #
  #   begin
  #     complex_operation_that_internally_calls_destroy!
  #   rescue ActiveRecord::RecordNotDestroyed => invalid
  #     puts invalid.record.errors
  #   end
  #
80
  class RecordNotDestroyed < ActiveRecordError
81 82
    attr_reader :record

83
    def initialize(message, record = nil)
84
      @record = record
85
      super(message)
86
    end
87 88
  end

89 90 91
  # Superclass for all database execution errors.
  #
  # Wraps the underlying database error as +original_exception+.
92
  class StatementInvalid < ActiveRecordError
93 94 95 96 97 98
    attr_reader :original_exception

    def initialize(message, original_exception = nil)
      super(message)
      @original_exception = original_exception
    end
99 100
  end

101 102
  # Defunct wrapper class kept for compatibility.
  # +StatementInvalid+ wraps the original exception now.
103 104 105 106 107 108 109 110 111 112 113
  class WrappedDatabaseException < StatementInvalid
  end

  # Raised when a record cannot be inserted because it would violate a uniqueness constraint.
  class RecordNotUnique < WrappedDatabaseException
  end

  # Raised when a record cannot be inserted or updated because it references a non-existent record.
  class InvalidForeignKey < WrappedDatabaseException
  end

114 115
  # Raised when number of bind variables in statement given to +:condition+ key
  # (for example, when using +find+ method) does not match number of expected
116
  # values supplied.
117
  #
118
  # For example, when there are two placeholders with only one value supplied:
119
  #
A
Akira Matsuda 已提交
120
  #   Location.where("lat = ? AND lng = ?", 53.7362)
121 122 123
  class PreparedStatementInvalid < ActiveRecordError
  end

124
  # Raised when a given database does not exist.
125
  class NoDatabaseError < StatementInvalid
126 127
  end

128 129 130 131
  # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
  # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
  # the page before the other.
  #
132 133
  # Read more about optimistic locking in ActiveRecord::Locking module
  # documentation.
134
  class StaleObjectError < ActiveRecordError
135
    attr_reader :record, :attempted_action
136

137
    def initialize(record, attempted_action)
138
      super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
139
      @record = record
140
      @attempted_action = attempted_action
141 142
    end

143 144
  end

145 146 147
  # Raised when association is being configured improperly or user tries to use
  # offset and limit together with +has_many+ or +has_and_belongs_to_many+
  # associations.
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  class ConfigurationError < ActiveRecordError
  end

  # Raised on attempt to update record that is instantiated as read only.
  class ReadOnlyRecord < ActiveRecordError
  end

  # ActiveRecord::Transactions::ClassMethods.transaction uses this exception
  # to distinguish a deliberate rollback from other exceptional situations.
  # Normally, raising an exception will cause the +transaction+ method to rollback
  # the database transaction *and* pass on the exception. But if you raise an
  # ActiveRecord::Rollback exception, then the database transaction will be rolled back,
  # without passing on the exception.
  #
  # For example, you could do this in your controller to rollback a transaction:
  #
  #   class BooksController < ActionController::Base
  #     def create
  #       Book.transaction do
  #         book = Book.new(params[:book])
  #         book.save!
  #         if today_is_friday?
  #           # The system must fail on Friday so that our support department
  #           # won't be out of job. We silently rollback this transaction
  #           # without telling the user.
  #           raise ActiveRecord::Rollback, "Call tech support!"
  #         end
  #       end
  #       # ActiveRecord::Rollback is the only exception that won't be passed on
  #       # by ActiveRecord::Base.transaction, so this line will still be reached
  #       # even on Friday.
  #       redirect_to root_url
  #     end
  #   end
  class Rollback < ActiveRecordError
  end

185 186
  # Raised when attribute has a name reserved by Active Record (when attribute
  # has name of one of Active Record instance methods).
187 188 189
  class DangerousAttributeError < ActiveRecordError
  end

R
Robin Dupret 已提交
190 191
  # Raised when unknown attributes are supplied via mass assignment.
  UnknownAttributeError = ActiveModel::UnknownAttributeError
192 193

  # Raised when an error occurred while doing a mass assignment to an attribute through the
194
  # +attributes=+ method. The exception has an +attribute+ property that is the name of the
195 196 197
  # offending attribute.
  class AttributeAssignmentError < ActiveRecordError
    attr_reader :exception, :attribute
198

199
    def initialize(message, exception, attribute)
200
      super(message)
201 202 203 204 205 206 207 208 209 210
      @exception = exception
      @attribute = attribute
    end
  end

  # Raised when there are multiple errors while doing a mass assignment through the +attributes+
  # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
  # objects, each corresponding to the error while assigning to an attribute.
  class MultiparameterAssignmentErrors < ActiveRecordError
    attr_reader :errors
211

212 213 214 215
    def initialize(errors)
      @errors = errors
    end
  end
216

A
Akshay Vishnoi 已提交
217
  # Raised when a primary key is needed, but not specified in the schema or model.
218 219 220 221
  class UnknownPrimaryKey < ActiveRecordError
    attr_reader :model

    def initialize(model)
222
      super("Unknown primary key for table #{model.table_name} in model #{model}.")
223 224 225 226
      @model = model
    end

  end
227

228 229 230 231 232 233 234 235
  # Raised when a relation cannot be mutated because it's already loaded.
  #
  #   class Task < ActiveRecord::Base
  #   end
  #
  #   relation = Task.all
  #   relation.loaded? # => true
  #
V
Vijay Dev 已提交
236 237 238
  #   # Methods which try to mutate a loaded relation fail.
  #   relation.where!(title: 'TODO')  # => ActiveRecord::ImmutableRelation
  #   relation.limit!(5)              # => ActiveRecord::ImmutableRelation
239 240
  class ImmutableRelation < ActiveRecordError
  end
241

242 243 244 245 246 247 248
  # TransactionIsolationError will be raised under the following conditions:
  #
  # * The adapter does not support setting the isolation level
  # * You are joining an existing open transaction
  # * You are creating a nested (savepoint) transaction
  #
  # The mysql, mysql2 and postgresql adapters support setting the transaction isolation level.
249 250
  class TransactionIsolationError < ActiveRecordError
  end
251
end