Rails 7.1 Now Allows ErrorReporter To Handle Several Error Classes
source link: https://blog.saeloun.com/2023/09/26/allow-error-reporter-to-handle-several-error-classes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Rails 7.1 Now Allows ErrorReporter To Handle Several Error Classes
Sep 26, 2023•
Mayank Agnihotri
I'm a React and Rails enthusiast with two years of experience creating innovative software solutions that improve business productivity. I work well in teams and am always up for challenging projects. Born and raised in Navi Mumbai, I enjoy gaming and travelling in my free time.
Recently Rails introduced a new way of handling errors which removes the need of using begin..end
and makes handling of multiple errors much more easier to read and write.
Read more about ErrorReporting API from here
For using error reporter we need an error subscriber.
What is a subscriber?
A Subscriber is any object with a report
method defined in it. Let’s have a look -
class ErrorSubscriber
attr_reader :error
def initialise(error: nil)
@error = error
end
def report(error, handled:, severity:, context:)
ErrorService.report_error(error:, handled:, severity:, context:)
end
end
Rails.error.subscribe(ErrorSubscriber.new)
The above code subscribes to our custom ErrorSubscriber
class which reports errors coming from our ErrorService
.
Before
Prior to the addition of error handler in Rails we used begin...end
block and rescue any errors being reported which were logged in the Rails console.
before
set_token(10)
rescue ArgumentError => e
puts e.message
end
def set_token
SecureRandom.base58(50)
end
Rescue with multiple exceptions -
EXCEPTIONS = [ArgumentError, StandarError]
begin
raise ArgumentError
raise StandardError
rescue *EXCEPTIONS => e
puts "Error: #{e.message} occurred."
end
After
After the change introduced in this PR, it is now possible to replace the above syntax with the handle
method.
Rails.error.handle(ArgumentError) do
set_token(10)
end
def set_token
SecureRandom.base58(50)
end
If the block does not raise any Exception/Error then result of the block will be returned or else it returns nil.
We can override this by providing fallback which returns the fallback
value if any error is raised instead of returning nil -
3.2.2 :001 > def token
3.2.2 :002 > SecureRandom.base58(50)
3.2.2 :003 > end
=> :token
3.2.2 :004 > result = Rails.error.handle(fallback: -> { token }) do
3.2.2 :005 > token(10)
3.2.2 :006 > end
=> "2n2TEr6RDjKCuoPH2xbj2Cm2AvMnEusAWw13grSAinQXnFpd5k"
Read about more options supported by ErrorHandler handle
method from here
Share this post!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK