Before Rails 7.1
# to handle a single error
begin
code_that_raises_exception
rescue ArgumentError => e
puts e.message
end
# to handle multiple errors
exceptions = [ArgumentError, StandarError]
begin
code_that_raises_argument_error
code_that_raises_standard_error
rescue *exceptions => e
puts "Error: #{e.message} occurred."
end
In Rails 7.1
@post = Post.new(params[:post])
Rails.error.handle(ActiveRecord::Errors, StandardError) do
@post.save!
end