Rails 7.1 allows ErrorReporter to handle several error classes
ErrorReporter
was added to Rails in version 7.0.
It was introduced as a way to provide a more consistent
and
standardized way to handle errors in the Rails applications.
To use ErrorReporter,
you need to call the Rails.error.handle
method whenever an error occurs.
This method will log the error
and
notify the appropriate error handlers.
You can also use ErrorReporter to raise custom errors.
Before Rails 7.1
Before Rails 7.0,
developers had to write their own custom code to handle errors.
This was done using the begin..rescue..end
block.
# 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
Rails 7 introduced the
Rails.error.
The handle
method would only accept
or
deal with an error of a particular type.
@post = Post.new(params[:post])
Rails.error.handle(ActiveRecord::Errors) do
@post.save!
end
If you try to pass multiple error handlers to the above method,
it will raise ArgumentError
as below:
@post = Post.new(params[:post])
Rails.error.handle(ActiveRecord::Errors, StandardError) do
@post.save!
end
=> wrong number of arguments (given 2, expected 0..1) (ArgumentError)
In Rails 7.1
Rails 7.1 allows ErrorReporter to handle several error classes.
@post = Post.new(params[:post])
Rails.error.handle(ActiveRecord::Errors, StandardError) do
@post.save!
end
The example code will run without generating any errors.
Any error class not passed to the handle
function will not be handled.
Rails.error.handle(IOError, ArgumentError) do
139 + 'abc' # raises TypeError
end
TypeError
is not passed as an argument to the handle
function,
139 + 'abc'
will not be rescued,
and
TypeError
gets raised.
To know more about this feature, please refer to this PR.